Unverified Commit 6e4f1e28 authored by გიორგი George Dav's avatar გიორგი George Dav Committed by GitHub

chore(examples): upgrade Auth0 example (#41284)

feat: [...auth0] 
Co-authored-by: 's avatarBalázs Orbán <18369201+balazsorban44@users.noreply.github.com>
parent 3d499a62
# Public Environment variables that can be used in the browser. AUTH0_ISSUER_BASE_URL="https://"
NEXT_PUBLIC_AUTH0_CLIENT_ID=TEST AUTH0_CLIENT_ID=
NEXT_PUBLIC_AUTH0_SCOPE="openid profile"
NEXT_PUBLIC_AUTH0_DOMAIN="http://example.com"
NEXT_PUBLIC_BASE_URL="http://localhost:3000"
NEXT_PUBLIC_REDIRECT_URI="/api/callback"
NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI="/"
# Secret environment variables only available to Node.js
AUTH0_CLIENT_SECRET= AUTH0_CLIENT_SECRET=
SESSION_COOKIE_SECRET= AUTH0_BASE_URL="http://localhost:3000"
SESSION_COOKIE_LIFETIME=7200 AUTH0_SECRET=
\ No newline at end of file
...@@ -6,8 +6,9 @@ This example shows how you can use `@auth0/nextjs-auth` to easily add authentica ...@@ -6,8 +6,9 @@ This example shows how you can use `@auth0/nextjs-auth` to easily add authentica
- Signing out - Signing out
- Loading the user on the server side and adding it as part of SSR ([`pages/advanced/ssr-profile.tsx`](pages/advanced/ssr-profile.tsx)) - Loading the user on the server side and adding it as part of SSR ([`pages/advanced/ssr-profile.tsx`](pages/advanced/ssr-profile.tsx))
- Loading the user on the client side and using fast/cached SSR pages ([`pages/index.tsx`](pages/index.tsx)) - Loading the user on the client side and using fast/cached SSR pages ([`pages/index.tsx`](pages/index.tsx))
- API Routes which can load the current user ([`pages/api/me.ts`](pages/api/me.ts)) - Loading the user on the client side and checking authentication CSR pages ([`pages/profile.tsx`](pages/profile.tsx))
- Using hooks to make the user available throughout the application ([`lib/user.ts`](lib/user.ts)) - Loading the user on the client side by accessing API (Serverless function) CSR pages ([`pages/advanced/api-profile.tsx`](pages/advanced/api-profile.tsx))
- Creates route handlers under the hood that perform different parts of the authentication flow ([`pages/auth/[...auth0].tsx`](pages/auth/[...auth0].tsx))
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/)
...@@ -50,14 +51,11 @@ cp .env.local.example .env.local ...@@ -50,14 +51,11 @@ cp .env.local.example .env.local
Then, open `.env.local` and add the missing environment variables: Then, open `.env.local` and add the missing environment variables:
- `NEXT_PUBLIC_AUTH0_DOMAIN` - Can be found in the Auth0 dashboard under `settings`. (Should be prefixed with `https://`) - `AUTH0_ISSUER_BASE_URL` - Can be found in the Auth0 dashboard under `settings`. (Should be prefixed with `https://`)
- `NEXT_PUBLIC_AUTH0_CLIENT_ID` - Can be found in the Auth0 dashboard under `settings`. - `AUTH0_CLIENT_ID` - Can be found in the Auth0 dashboard under `settings`.
- `AUTH0_CLIENT_SECRET` - Can be found in the Auth0 dashboard under `settings`. - `AUTH0_CLIENT_SECRET` - Can be found in the Auth0 dashboard under `settings`.
- `NEXT_PUBLIC_BASE_URL` - The base url of the application. - `AUTH0_BASE_URL` - The base url of the application.
- `NEXT_PUBLIC_REDIRECT_URI` - The relative url path where Auth0 redirects back to. - `AUTH0_SECRET` - Has to be at least 32 characters. You can use [this generator](https://generate-secret.vercel.app/32) to generate a value.
- `NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI` - Where to redirect after logging out.
- `SESSION_COOKIE_SECRET` - A unique secret used to encrypt the cookies, has to be at least 32 characters. You can use [this generator](https://generate-secret.vercel.app/32) to generate a value.
- `SESSION_COOKIE_LIFETIME` - How long a session lasts in seconds. The default is 2 hours.
## Deploy on Vercel ## Deploy on Vercel
......
...@@ -20,12 +20,17 @@ const Header = ({ user, loading }: HeaderProps) => { ...@@ -20,12 +20,17 @@ const Header = ({ user, loading }: HeaderProps) => {
<a>About</a> <a>About</a>
</Link> </Link>
</li> </li>
<li>
<Link href="/advanced/api-profile">
<a>API rendered profile (advanced)</a>
</Link>
</li>
{!loading && {!loading &&
(user ? ( (user ? (
<> <>
<li> <li>
<Link href="/profile"> <Link href="/profile">
<a>Client-rendered profile</a> <a>Client rendered profile</a>
</Link> </Link>
</li> </li>
<li> <li>
...@@ -34,12 +39,12 @@ const Header = ({ user, loading }: HeaderProps) => { ...@@ -34,12 +39,12 @@ const Header = ({ user, loading }: HeaderProps) => {
</Link> </Link>
</li> </li>
<li> <li>
<a href="/api/logout">Logout</a> <a href="/api/auth/logout">Logout</a>
</li> </li>
</> </>
) : ( ) : (
<li> <li>
<a href="/api/login">Login</a> <a href="/api/auth/login">Login</a>
</li> </li>
))} ))}
</ul> </ul>
...@@ -63,8 +68,9 @@ const Header = ({ user, loading }: HeaderProps) => { ...@@ -63,8 +68,9 @@ const Header = ({ user, loading }: HeaderProps) => {
} }
li { li {
margin-right: 1rem; margin-right: 1rem;
padding-right: 2rem;
} }
li:nth-child(2) { li:nth-child(3) {
margin-right: auto; margin-right: auto;
} }
a { a {
......
import { initAuth0 } from '@auth0/nextjs-auth0'
import { SignInWithAuth0 } from '@auth0/nextjs-auth0/dist/instance'
const auth0: SignInWithAuth0 = initAuth0({
secret: process.env.SESSION_COOKIE_SECRET,
issuerBaseURL: process.env.NEXT_PUBLIC_AUTH0_DOMAIN,
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
clientID: process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID,
clientSecret: process.env.AUTH0_CLIENT_SECRET,
routes: {
callback:
process.env.NEXT_PUBLIC_REDIRECT_URI ||
'http://localhost:3000/api/callback',
postLogoutRedirect:
process.env.NEXT_PUBLIC_POST_LOGOUT_REDIRECT_URI ||
'http://localhost:3000',
},
authorizationParams: {
response_type: 'code',
scope: process.env.NEXT_PUBLIC_AUTH0_SCOPE,
},
session: {
absoluteDuration: Number(process.env.SESSION_COOKIE_LIFETIME),
},
})
export default auth0
import { UserProfile } from '@auth0/nextjs-auth0'
import { useState, useEffect } from 'react'
export async function fetchUser(cookie = '') {
if (typeof window !== 'undefined' && window.__user) {
return window.__user
}
const res = await fetch(
'/api/me',
cookie
? {
headers: {
cookie,
},
}
: {}
)
if (!res.ok) {
delete window.__user
return null
}
const json: UserProfile = await res.json()
if (typeof window !== 'undefined') {
window.__user = json
}
return json
}
export function useFetchUser(
{ required }: { required: boolean } = { required: false }
) {
const [loading, setLoading] = useState(
() => !(typeof window !== 'undefined' && window.__user)
)
const [user, setUser] = useState(() => {
if (typeof window === 'undefined') {
return null
}
return window.__user || null
})
useEffect(
() => {
if (!loading && user) {
return
}
setLoading(true)
let isMounted = true
fetchUser().then((user) => {
// Only set the user if the component is still mounted
if (isMounted) {
// When the user is not logged in but login is required
if (required && !user) {
window.location.href = '/api/login'
return
}
setUser(user)
setLoading(false)
}
})
return () => {
isMounted = false
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
return { user, loading }
}
import { UserProvider } from '@auth0/nextjs-auth0'
export default function App({ Component, pageProps }) {
// optionally pass the 'user' prop from pages that require server-side
// rendering to prepopulate the 'useUser' hook.
const { user } = pageProps
return (
<UserProvider user={user}>
<Component {...pageProps} />
</UserProvider>
)
}
import { useUser } from '@auth0/nextjs-auth0'
import Layout from '../components/layout' import Layout from '../components/layout'
import { useFetchUser } from '../lib/user'
const About = () => { const About = () => {
const { user, loading } = useFetchUser() const { user, isLoading } = useUser()
return ( return (
<Layout user={user} loading={loading}> <Layout user={user} loading={isLoading}>
<h1>About</h1> <h1>About</h1>
<p> <p>
This is the about page, navigating between this page and <i>Home</i> is This project shows different ways to display Profile info: using{' '}
always pretty fast. However, when you navigate to the <i>Profile</i>{' '} <i>Client rendered</i>, <i>Server rendered</i>, and <i>API rendered</i>
page it takes more time because it uses SSR to fetch the user first; </p>
<p>
Navigating between this page and <i>Home</i> is always pretty fast.
However, when you navigate to the <i>Server rendered profile</i> page it
takes more time because it uses SSR to fetch the user and then to
display it
</p> </p>
</Layout> </Layout>
) )
......
import { useEffect, useState } from 'react'
import { useUser } from '@auth0/nextjs-auth0'
import Layout from '../../components/layout'
const ApiProfile = () => {
const { user, isLoading } = useUser()
const [data, setData] = useState(null)
useEffect(() => {
;(async () => {
const res = await fetch('/api/protected-api')
const data = await res.json()
setData(data)
})()
}, [])
return (
<Layout user={user} loading={isLoading}>
<h1>Profile</h1>
<div>
<h3>Public page (client rendered)</h3>
<p>We are fetching data on the client-side :</p>
<p>By making request to '/api/protected-api' serverless function</p>
<p>so without a valid session cookie will fail</p>
<p>{JSON.stringify(data)}</p>
</div>
</Layout>
)
}
// Public route.(CSR) also accessing API from the client-side.
// data is not cached when redirecting between pages.
export default ApiProfile
import { GetServerSideProps } from 'next' import { withPageAuthRequired } from '@auth0/nextjs-auth0'
// This import is only included in the server build, because it's only used by getServerSideProps
import auth0 from '../../lib/auth0'
import Layout from '../../components/layout' import Layout from '../../components/layout'
import { User } from '../../interfaces' import { User } from '../../interfaces'
...@@ -9,7 +6,7 @@ type ProfileProps = { ...@@ -9,7 +6,7 @@ type ProfileProps = {
user: User user: User
} }
const Profile = ({ user }: ProfileProps) => { export default function Profile({ user }: ProfileProps) {
return ( return (
<Layout user={user}> <Layout user={user}>
<h1>Profile</h1> <h1>Profile</h1>
...@@ -24,17 +21,6 @@ const Profile = ({ user }: ProfileProps) => { ...@@ -24,17 +21,6 @@ const Profile = ({ user }: ProfileProps) => {
) )
} }
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { // Protected route, checking authentication status before rendering the page.(SSR)
// Here you can check authentication status directly before rendering the page, // It's slower than a static page with client side authentication
// however the page would be a serverless function, which is more expensive and export const getServerSideProps = withPageAuthRequired()
// slower than a static page with client side authentication
const session = await auth0.getSession(req, res)
if (!session || !session.user) {
return { redirect: { destination: '/api/login', permanent: false } }
}
return { props: { user: session.user } }
}
export default Profile
import { handleAuth } from '@auth0/nextjs-auth0'
export default handleAuth()
import type { NextApiRequest, NextApiResponse } from 'next'
import auth0 from '../../lib/auth0'
const callback = async (req: NextApiRequest, res: NextApiResponse) => {
try {
await auth0.handleCallback(req, res)
} catch (error) {
console.error(error)
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'
const login = async (req: NextApiRequest, res: NextApiResponse) => {
try {
await auth0.handleLogin(req, res)
} catch (error) {
console.error(error)
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'
const logout = async (req: NextApiRequest, res: NextApiResponse) => {
try {
await auth0.handleLogout(req, res)
} catch (error) {
console.error(error)
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'
const me = async (req: NextApiRequest, res: NextApiResponse) => {
try {
await auth0.handleProfile(req, res)
} catch (error) {
console.error(error)
const errorMessage =
error instanceof Error ? error.message : 'Internal server error'
res.status(500).end(errorMessage)
}
}
export default me
import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0'
// Serverless function
// Protected API, requests to '/api/protected' without a valid session cookie will fail
async function handle(req, res) {
const { user } = getSession(req, res)
try {
res.status(200).json({
session: 'true',
id: user.sub,
nickname: user.nickname,
})
} catch (e) {
res.status(500).json({ error: 'Unable to fetch', description: e })
}
}
export default withApiAuthRequired(handle)
import { useUser } from '@auth0/nextjs-auth0'
import Layout from '../components/layout' import Layout from '../components/layout'
import { useFetchUser } from '../lib/user'
const Home = () => { const Home = () => {
const { user, loading } = useFetchUser() const { user, isLoading } = useUser()
return ( return (
<Layout user={user} loading={loading}> <Layout user={user} loading={isLoading}>
<h1>Next.js and Auth0 Example</h1> <h1>Next.js and Auth0 Example</h1>
{loading && <p>Loading login info...</p>} {isLoading && <p>Loading login info...</p>}
{!loading && !user && ( {!isLoading && !user && (
<> <>
<p> <p>
To test the login click in <i>Login</i> To test the login click in <i>Login</i>
</p> </p>
<p> <p>
Once you have logged in you should be able to click in{' '} Once you have logged in you should be able to navigate between
<i>Profile</i> and <i>Logout</i> protected routes: client rendered, server rendered profile pages,
and <i>Logout</i>
</p> </p>
</> </>
)} )}
...@@ -34,4 +35,5 @@ const Home = () => { ...@@ -34,4 +35,5 @@ const Home = () => {
) )
} }
// fast/cached SSR page
export default Home export default Home
// This import is only needed when checking authentication status directly from getInitialProps import { withPageAuthRequired } from '@auth0/nextjs-auth0'
// import auth0 from '../lib/auth0'
import { useFetchUser } from '../lib/user'
import Layout from '../components/layout' import Layout from '../components/layout'
import { User } from '../interfaces' import { User } from '../interfaces'
...@@ -23,14 +21,13 @@ const ProfileCard = ({ user }: ProfileCardProps) => { ...@@ -23,14 +21,13 @@ const ProfileCard = ({ user }: ProfileCardProps) => {
) )
} }
const Profile = () => { const Profile = ({ user, isLoading }) => {
const { user, loading } = useFetchUser({ required: true })
return ( return (
<Layout user={user} loading={loading}> <Layout user={user} loading={isLoading}>
{loading ? <>Loading...</> : <ProfileCard user={user} />} {isLoading ? <>Loading...</> : <ProfileCard user={user} />}
</Layout> </Layout>
) )
} }
export default Profile // Protected route, checking user authentication client-side.(CSR)
export default withPageAuthRequired(Profile)
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