Unverified Commit 55560e0c authored by Max Proske's avatar Max Proske Committed by GitHub

Convert auth0 example to TypeScript (#38087)

Converted auth0 example over to TypeScript to match the Contribution guidelines, and got rid of the `tslib` dependency.

Note: You must copy `.env.local.example` to `.env.local`, or you will encounter "TypeError: "secret" is required" at build time.

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm lint`
- [X] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
parent bbffaea7
# Public Environment variables that can be used in the browser. # Public Environment variables that can be used in the browser.
NEXT_PUBLIC_AUTH0_CLIENT_ID= NEXT_PUBLIC_AUTH0_CLIENT_ID=TEST
NEXT_PUBLIC_AUTH0_SCOPE="openid profile" NEXT_PUBLIC_AUTH0_SCOPE="openid profile"
NEXT_PUBLIC_AUTH0_DOMAIN= NEXT_PUBLIC_AUTH0_DOMAIN="http://example.com"
NEXT_PUBLIC_BASE_URL="http://localhost:3000" NEXT_PUBLIC_BASE_URL="http://localhost:3000"
NEXT_PUBLIC_REDIRECT_URI="/api/callback" NEXT_PUBLIC_REDIRECT_URI="/api/callback"
NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI="/" NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI="/"
......
...@@ -32,3 +32,6 @@ yarn-error.log* ...@@ -32,3 +32,6 @@ yarn-error.log*
# vercel # vercel
.vercel .vercel
# typescript
*.tsbuildinfo
...@@ -4,10 +4,10 @@ This example shows how you can use `@auth0/nextjs-auth` to easily add authentica ...@@ -4,10 +4,10 @@ This example shows how you can use `@auth0/nextjs-auth` to easily add authentica
- Signing in - Signing in
- Signing out - Signing out
- Loading the user on the server side and adding it as part of SSR ([`pages/advanced/ssr-profile.js`](pages/advanced/ssr-profile.js)) - Loading the user on the server side and adding it as part of SSR ([`pages/advanced/ssr-profile.ts`](pages/advanced/ssr-profile.ts))
- Loading the user on the client side and using fast/cached SSR pages ([`pages/index.js`](pages/index.js)) - Loading the user on the client side and using fast/cached SSR pages ([`pages/index.ts`](pages/index.ts))
- API Routes which can load the current user ([`pages/api/me.js`](pages/api/me.js)) - API Routes which can load the current user ([`pages/api/me.ts`](pages/api/me.ts))
- Using hooks to make the user available throughout the application ([`lib/user.js`](lib/user.js)) - Using hooks to make the user available throughout the application ([`lib/user.ts`](lib/user.ts))
Read more: [https://auth0.com/blog/ultimate-guide-nextjs-authentication-auth0/](https://auth0.com/blog/ultimate-guide-nextjs-authentication-auth0/) Read more: [https://auth0.com/blog/ultimate-guide-nextjs-authentication-auth0/](https://auth0.com/blog/ultimate-guide-nextjs-authentication-auth0/)
......
export {}
declare global {
interface Window {
__user: any
}
}
import Link from 'next/link' import Link from 'next/link'
function Header({ user, loading }) { type HeaderProps = {
user?: any
loading: boolean
}
const Header = ({ user, loading }: HeaderProps) => {
return ( return (
<header> <header>
<nav> <nav>
......
import Head from 'next/head' import Head from 'next/head'
import Header from './header' import Header from './header'
function Layout({ user, loading = false, children }) { type LayoutProps = {
user?: any
loading?: boolean
children: React.ReactNode
}
const Layout = ({ user, loading = false, children }: LayoutProps) => {
return ( return (
<> <>
<Head> <Head>
......
export type User = {
email: string
email_verified: boolean
name: string
nickname: string
picture: string
sub: string
updated_at: string
}
import { initAuth0 } from '@auth0/nextjs-auth0' import { initAuth0 } from '@auth0/nextjs-auth0'
import { SignInWithAuth0 } from '@auth0/nextjs-auth0/dist/instance'
export default initAuth0({ const auth0: SignInWithAuth0 = initAuth0({
secret: process.env.SESSION_COOKIE_SECRET, secret: process.env.SESSION_COOKIE_SECRET,
issuerBaseURL: process.env.NEXT_PUBLIC_AUTH0_DOMAIN, issuerBaseURL: process.env.NEXT_PUBLIC_AUTH0_DOMAIN,
baseURL: process.env.NEXT_PUBLIC_BASE_URL, baseURL: process.env.NEXT_PUBLIC_BASE_URL,
...@@ -19,6 +20,8 @@ export default initAuth0({ ...@@ -19,6 +20,8 @@ export default initAuth0({
scope: process.env.NEXT_PUBLIC_AUTH0_SCOPE, scope: process.env.NEXT_PUBLIC_AUTH0_SCOPE,
}, },
session: { session: {
absoluteDuration: process.env.SESSION_COOKIE_LIFETIME, absoluteDuration: Number(process.env.SESSION_COOKIE_LIFETIME),
}, },
}) })
export default auth0
import { UserProfile } from '@auth0/nextjs-auth0'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
export async function fetchUser(cookie = '') { export async function fetchUser(cookie = '') {
...@@ -21,14 +22,16 @@ export async function fetchUser(cookie = '') { ...@@ -21,14 +22,16 @@ export async function fetchUser(cookie = '') {
return null return null
} }
const json = await res.json() const json: UserProfile = await res.json()
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
window.__user = json window.__user = json
} }
return json return json
} }
export function useFetchUser({ required } = {}) { export function useFetchUser(
{ required }: { required: boolean } = { required: false }
) {
const [loading, setLoading] = useState( const [loading, setLoading] = useState(
() => !(typeof window !== 'undefined' && window.__user) () => !(typeof window !== 'undefined' && window.__user)
) )
......
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
...@@ -6,10 +6,15 @@ ...@@ -6,10 +6,15 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@auth0/nextjs-auth0": "^1.4.2", "@auth0/nextjs-auth0": "^1.9.1",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "^18.2.0",
"react-dom": "^17.0.2", "react-dom": "^18.2.0"
"tslib": "^2.2.0" },
"devDependencies": {
"@types/node": "^18.0.0",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"typescript": "^4.7.4"
} }
} }
import Layout from '../components/layout' import Layout from '../components/layout'
import { useFetchUser } from '../lib/user' import { useFetchUser } from '../lib/user'
function About() { const About = () => {
const { user, loading } = useFetchUser() const { user, loading } = useFetchUser()
return ( return (
......
import { GetServerSideProps } from 'next'
// This import is only included in the server build, because it's only used by getServerSideProps // This import is only included in the server build, because it's only used by getServerSideProps
import auth0 from '../../lib/auth0' import auth0 from '../../lib/auth0'
import Layout from '../../components/layout' import Layout from '../../components/layout'
import { User } from '../../interfaces'
type ProfileProps = {
user: User
}
function Profile({ user }) { const Profile = ({ user }: ProfileProps) => {
return ( return (
<Layout user={user}> <Layout user={user}>
<h1>Profile</h1> <h1>Profile</h1>
...@@ -17,18 +24,14 @@ function Profile({ user }) { ...@@ -17,18 +24,14 @@ function Profile({ user }) {
) )
} }
export async function getServerSideProps({ req, res }) { export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
// Here you can check authentication status directly before rendering the page, // Here you can check authentication status directly before rendering the page,
// however the page would be a serverless function, which is more expensive and // however the page would be a serverless function, which is more expensive and
// slower than a static page with client side authentication // slower than a static page with client side authentication
const session = await auth0.getSession(req, res) const session = await auth0.getSession(req, res)
if (!session || !session.user) { if (!session || !session.user) {
res.writeHead(302, { return { redirect: { destination: '/api/login', permanent: false } }
Location: '/api/login',
})
res.end()
return
} }
return { props: { user: session.user } } return { props: { user: session.user } }
......
import type { NextApiRequest, NextApiResponse } from 'next'
import auth0 from '../../lib/auth0' import auth0 from '../../lib/auth0'
export default async function callback(req, res) { const callback = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
await auth0.handleCallback(req, res) await auth0.handleCallback(req, res)
} catch (error) { } catch (error) {
console.error(error) console.error(error)
res.status(error.status || 500).end(error.message) const errorMessage =
error instanceof Error ? error.message : 'Internal server error'
res.status(500).end(errorMessage)
} }
} }
export default callback
import type { NextApiRequest, NextApiResponse } from 'next'
import auth0 from '../../lib/auth0' import auth0 from '../../lib/auth0'
export default async function login(req, res) { const login = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
await auth0.handleLogin(req, res) await auth0.handleLogin(req, res)
} catch (error) { } catch (error) {
console.error(error) console.error(error)
res.status(error.status || 500).end(error.message) const errorMessage =
error instanceof Error ? error.message : 'Internal server error'
res.status(500).end(errorMessage)
} }
} }
export default login
import type { NextApiRequest, NextApiResponse } from 'next'
import auth0 from '../../lib/auth0' import auth0 from '../../lib/auth0'
export default async function logout(req, res) { const logout = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
await auth0.handleLogout(req, res) await auth0.handleLogout(req, res)
} catch (error) { } catch (error) {
console.error(error) console.error(error)
res.status(error.status || 500).end(error.message) const errorMessage =
error instanceof Error ? error.message : 'Internal server error'
res.status(500).end(errorMessage)
} }
} }
export default logout
import type { NextApiRequest, NextApiResponse } from 'next'
import auth0 from '../../lib/auth0' import auth0 from '../../lib/auth0'
export default async function me(req, res) { const me = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
await auth0.handleProfile(req, res) await auth0.handleProfile(req, res)
} catch (error) { } catch (error) {
console.error(error) console.error(error)
res.status(error.status || 500).end(error.message) const errorMessage =
error instanceof Error ? error.message : 'Internal server error'
res.status(500).end(errorMessage)
} }
} }
export default me
import Layout from '../components/layout' import Layout from '../components/layout'
import { useFetchUser } from '../lib/user' import { useFetchUser } from '../lib/user'
function Home() { const Home = () => {
const { user, loading } = useFetchUser() const { user, loading } = useFetchUser()
return ( return (
......
...@@ -2,8 +2,13 @@ ...@@ -2,8 +2,13 @@
// import auth0 from '../lib/auth0' // import auth0 from '../lib/auth0'
import { useFetchUser } from '../lib/user' import { useFetchUser } from '../lib/user'
import Layout from '../components/layout' import Layout from '../components/layout'
import { User } from '../interfaces'
function ProfileCard({ user }) { type ProfileCardProps = {
user: User
}
const ProfileCard = ({ user }: ProfileCardProps) => {
return ( return (
<> <>
<h1>Profile</h1> <h1>Profile</h1>
...@@ -18,7 +23,7 @@ function ProfileCard({ user }) { ...@@ -18,7 +23,7 @@ function ProfileCard({ user }) {
) )
} }
function Profile() { const Profile = () => {
const { user, loading } = useFetchUser({ required: true }) const { user, loading } = useFetchUser({ required: true })
return ( return (
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "additional.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment