From a6e5870216b504fad85904afce27e0783678af5e Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 17:45:17 +0200 Subject: [PATCH 01/18] Update download.md Edited Callback URL path --- articles/quickstart/webapp/nextjs/download.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/download.md b/articles/quickstart/webapp/nextjs/download.md index e1adb730a4..b80e4d475b 100644 --- a/articles/quickstart/webapp/nextjs/download.md +++ b/articles/quickstart/webapp/nextjs/download.md @@ -4,7 +4,7 @@ To run the sample follow these steps: 1) Set the **Allowed Callback URLs** in the Application Settings to ```text -http://localhost:3000/api/auth/callback +http://localhost:3000/auth/callback ``` 2) Set **Allowed Logout URLs** in the Application Settings to From cffd413d701693b7afff01263b29137639aae52d Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 17:55:42 +0200 Subject: [PATCH 02/18] Update index.yml Updated author and Next.js requirements --- articles/quickstart/webapp/nextjs/index.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/index.yml b/articles/quickstart/webapp/nextjs/index.yml index ad6a5b3b9a..e108ef728e 100644 --- a/articles/quickstart/webapp/nextjs/index.yml +++ b/articles/quickstart/webapp/nextjs/index.yml @@ -11,8 +11,8 @@ language: framework: - Next.js author: - name: Rita Zerrizuela - email: rita.zerrizuela@auth0.com + name: Carlos Fung + email: carlos.fung@auth0.com community: false topics: @@ -23,7 +23,7 @@ seo_alias: nextjs show_releases: true show_steps: true requirements: - - Next.js 13.4+ + - Next.js 15.2.4+ default_article: 01-login articles: - 01-login From 8bbe47c0c981c92bf19e7b8ad4b7fb4abe05ec97 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 17:58:45 +0200 Subject: [PATCH 03/18] Update index.yml reverted author info --- articles/quickstart/webapp/nextjs/index.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/index.yml b/articles/quickstart/webapp/nextjs/index.yml index e108ef728e..09ceb743f6 100644 --- a/articles/quickstart/webapp/nextjs/index.yml +++ b/articles/quickstart/webapp/nextjs/index.yml @@ -11,8 +11,8 @@ language: framework: - Next.js author: - name: Carlos Fung - email: carlos.fung@auth0.com + name: Rita Zerrizuela + email: rita.zerrizuelag@auth0.com community: false topics: From 210d388579580d1b57ecfa2ccc74558712570cb9 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 19:45:58 +0200 Subject: [PATCH 04/18] Update 01-login.md Updated Quickstart from V3 -> V4. --- articles/quickstart/webapp/nextjs/01-login.md | 227 +++++++++++------- 1 file changed, 137 insertions(+), 90 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 7bffa91d5f..b6e670f216 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -14,7 +14,7 @@ useCase: quickstart --- -<%= include('../_includes/_getting_started', { library: 'Next.js', callback: 'http://localhost:3000/api/auth/callback' }) %> +<%= include('../_includes/_getting_started', { library: 'Next.js', callback: 'http://localhost:3000/auth/callback' }) %> <%= include('../../../_includes/_logout_url', { returnTo: 'http://localhost:3000' }) %> @@ -23,98 +23,138 @@ useCase: quickstart Run the following command within your project directory to install the Auth0 Next.js SDK: ```sh -npm install @auth0/nextjs-auth0@3 +npm install @auth0/nextjs-auth0 ``` The SDK exposes methods and variables that help you integrate Auth0 with your Next.js application using Route Handlers on the backend and React Context with React Hooks on the frontend. ### Configure the SDK -In the root directory of your project, add the file `.env.local` with the following environment variables: +In the root directory of your project, create the file `.env.local` with the following environment variables: ```sh AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value' -AUTH0_BASE_URL='http://localhost:3000' -AUTH0_ISSUER_BASE_URL='https://${account.namespace}' +APP_BASE_URL='http://localhost:3000' +AUTH0_DOMAIN='https://${account.namespace}' AUTH0_CLIENT_ID='${account.clientId}' AUTH0_CLIENT_SECRET='${account.clientSecret}' +'If your application is API authorized add the variables AUTH0_AUDIENCE and AUTH0_SCOPE' +AUTH0_AUDIENCE='your_auth_api_identifier' +AUTH0_SCOPE='openid profile email read:shows' ``` - `AUTH0_SECRET`: A long secret value used to encrypt the session cookie. You can generate a suitable string using `openssl rand -hex 32` on the command line. -- `AUTH0_BASE_URL`: The base URL of your application. -- `AUTH0_ISSUER_BASE_URL`: The URL of your Auth0 tenant domain. If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab. +- `APP_BASE_URL`: The base URL of your application. +- `AUTH0_DOMAIN`: The URL of your Auth0 tenant domain. If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab. - `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID. - `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret. -The SDK will read these values from the Node.js process environment and automatically configure itself. +The SDK will read these values from the Node.js process environment and configure itself automatically. -### Add the dynamic API route handler +::: note +Manually add the values for `AUTH0_AUDIENCE` and `AUTH_SCOPE` to the file `lib/auth0.js`. These values are not configured automatically. +::: -Create a file at `app/api/auth/[auth0]/route.js`. This is your Route Handler file with a Dynamic Route Segment. +### Create the Auth0 SDK Client -Then, import the `handleAuth` method from the SDK and call it from the `GET` export. +Create a file at `lib/auth0.js` to add an instance of the Auth0 client. This instance provides methods for handling authentication, sesssions and user data. ```javascript -// app/api/auth/[auth0]/route.js -import { handleAuth } from '@auth0/nextjs-auth0'; - -export const GET = handleAuth(); +// lib/auth0.js + +import { Auth0Client } from "@auth0/nextjs-auth0/server"; + +// Initialize the Auth0 client +export const auth0 = new Auth0Client({ + // Options are loaded from environment variables by default + // Ensure necessary environment variables are properly set + // domain: process.env.AUTH0_DOMAIN, + // clientId: process.env.AUTH0_CLIENT_ID, + // clientSecret: process.env.AUTH0_CLIENT_SECRET, + // appBaseUrl: process.env.APP_BASE_URL, + // secret: process.env.AUTH0_SECRET, + + authorizationParameters: { + // In v4, the AUTH0_SCOPE and AUTH0_AUDIENCE environment variables for API authorized applications are no longer automatically picked up by the SDK. + // Instead, we need to provide the values explicitly. + scope: process.env.AUTH0_SCOPE, + audience: process.env.AUTH0_AUDIENCE, + } +}); ``` -This creates the following routes: - -- `/api/auth/login`: The route used to perform login with Auth0. -- `/api/auth/logout`: The route used to log the user out. -- `/api/auth/callback`: The route Auth0 will redirect the user to after a successful login. -- `/api/auth/me`: The route to fetch the user profile from. - -::: note -This QuickStart targets the Next.js App Router. If you're using the Pages Router, check out the example in the SDK's README. -::: - -### Add the `UserProvider` component - -On the frontend side, the SDK uses React Context to manage the authentication state of your users. To make that state available to all your pages, you need to override the Root Layout component and wrap the `` tag with a `UserProvider` in the file `app/layout.jsx`. -Create the file `app/layout.jsx` as follows: +### Add the dynamic API route handler -```jsx -// app/layout.jsx -import { UserProvider } from '@auth0/nextjs-auth0/client'; +Create a file at `app/api/shows/route.js`. This is your route Handler file using Dynamic Route Segment. The file declares a `GET` export to call the `shows()` method from the SDK to create the API routes. import the `handleAuth` method from the SDK and call it from the `GET` export. -export default function RootLayout({ children }) { - return ( - - - {children} - - - ); -} +```javascript +// app/api/shows/route.js +import { NextResponse } from 'next/server'; +import { auth0 } from '../../../lib/auth0'; + +export const GET = async function shows() { + try { + const session = await auth0.getSession(); + + if (!session) { + return NextResponse.json( + { error: 'Not authenticated' }, + { status: 401 } + ); + } + + const res = new NextResponse(); + const { token: accessToken } = await auth0.getAccessToken(); + const apiPort = process.env.API_PORT || 3001; + const response = await fetch(`http://localhost:${apiPort}/api/shows`, { + headers: { + Authorization: `Bearer ${accessToken}` + } + }); + const shows = await response.json(); + + return NextResponse.json(shows, res); + } catch (error) { + return NextResponse.json({ error: error.message }, { status: error.status || 500 }); + } +}; ``` -The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook. +Upon execution the following routes for your customers are available: -:::panel Checkpoint -Now that you have added the dynamic route and `UserProvider`, run your application to verify that your application is not throwing any errors related to Auth0. -::: +- `/auth/login`: The route to perform login with Auth0. +- `/auth/logout`: The route to log the user out. +- `/auth/callback`: The route Auth0 will redirect the user to after a successful login. +- `/auth/profile`: The route to fetch the user profile. +- `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available). +- `/auth/backchannell-logout`: The route to receive a logout_token when a configured Back-Channel Logout initiator occurs. + +To learn more about routing in Auth0, read Add the dynamic API route. ## Add Login to Your Application -Users can now log in to your application by visiting the `/api/auth/login` route provided by the SDK. Add a link that points to the login route using an **anchor tag**. Clicking it redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 will redirect your users back to your application. - -:::note -Next linting rules might suggest using the `Link` component instead of an anchor tag. The `Link` component is meant to perform client-side transitions between pages. As the link points to an API route and not to a page, you should keep it as an anchor tag. -::: +Users can now log in to your application at `/api/auth/login` route provided by the SDK. Use an **anchor tag** to add a link to the login route, the route redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 redirects your users back to your application. ```html -Login +Login ``` +:::note +Next suggest using Link components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed. +::: + :::panel Checkpoint -Add the login link to your application. When you click it, verify that your Next.js application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider. +Add the login link to your application. Select it and verify that your Next.js application redirects you to the Auth0 Universal Login page and that you can now log in or sign up using a username and password or a social provider. Once that's complete, verify that Auth0 redirects back to your application. + +If you are following along with the sample app project from the top of this page, run the command: + +```sh +npm i && npm run dev +``` +and visit http://localhost:3000 in your browser. ::: ![Auth0 Universal Login](/media/quickstarts/universal-login.png) @@ -123,14 +163,14 @@ Once that's complete, verify that Auth0 redirects back to your application. ## Add Logout to Your Application -Now that you can log in to your Next.js application, you need a way to log out. Add a link that points to the `/api/auth/logout` API route. Clicking it redirects your users to your Auth0 logout endpoint (`https://YOUR_DOMAIN/v2/logout`) and then immediately redirects them back to your application. +Now that you can log in to your Next.js application, you need a way to log out. Add a link that points to the `/auth/logout` API route. To learn more, read Log Users out of Auth0 with OIDC Endpoint. ```html -Logout +Logout ``` :::panel Checkpoint -Add the logout link to your application. When you click it, verify that your Next.js application redirects you to the address you specified as one of the "Allowed Logout URLs" in the "Settings". +Add the logout link to your application. When you select it, verify that your Next.js application redirects you to the address you specified as one of the "Allowed Logout URLs" in the application "Settings". ::: ## Show User Profile Information @@ -143,25 +183,45 @@ The profile information is available through the `user` property exposed by the ```jsx 'use client'; - -import { useUser } from '@auth0/nextjs-auth0/client'; - -export default function ProfileClient() { - const { user, error, isLoading } = useUser(); - - if (isLoading) return
Loading...
; - if (error) return
{error.message}
; - +import React from 'react'; +import { Row, Col } from 'reactstrap'; +import { useUser } from '@auth0/nextjs-auth0'; +import Loading from '../../components/Loading'; +import Highlight from '../../components/Highlight'; + +export default function Profile() { + const { user, isLoading } = useUser(); return ( - user && ( -
- {user.name} -

{user.name}

-

{user.email}

-
- ) + <> + {isLoading && } + {user && ( + <> + + + Profile + + +

{user.name}

+

+ {user.email} +

+ +
+ + {JSON.stringify(user, null, 2)} + + + )} + ); } + ``` The `user` property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors: @@ -175,21 +235,13 @@ The `user` property contains sensitive information and artifacts related to the The profile information is available through the `user` property exposed by the `getSession` function. Take this Server Component as an example of how to use it: ```jsx -import { getSession } from '@auth0/nextjs-auth0'; +import { auth0 } from "@/lib/auth0"; export default async function ProfileServer() { - const { user } = await getSession(); - - return ( - user && ( -
- {user.name} -

{user.name}

-

{user.email}

-
- ) - ); + const { user } = await auth0.getSession(); + return ( user && (
{user.name}/

{user.name}

{user.email}

) ); } + ``` :::panel Checkpoint @@ -198,9 +250,4 @@ Verify that you can display the `user.name` or nextjs-auth0 in more advanced use cases: - -- Protecting a Server Side Rendered (SSR) Page -- Protecting a Client Side Rendered (CSR) Page -- Protect an API Route -- Access an External API from an API Route +We put together a few examples on how to use nextjs-auth0 for more advanced use cases. From 9b44c89a8f15da0080cabfa2a777e11a90bc373d Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 20:09:46 +0200 Subject: [PATCH 05/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index b6e670f216..a57ef2a927 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -44,15 +44,16 @@ AUTH0_SCOPE='openid profile email read:shows' ``` - `AUTH0_SECRET`: A long secret value used to encrypt the session cookie. You can generate a suitable string using `openssl rand -hex 32` on the command line. -- `APP_BASE_URL`: The base URL of your application. -- `AUTH0_DOMAIN`: The URL of your Auth0 tenant domain. If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab. -- `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID. -- `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret. +- `APP_BASE_URL`: The base URL of your application +- `AUTH0_DOMAIN`: The URL of your Auth0 tenant domain +- `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID +- `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret The SDK will read these values from the Node.js process environment and configure itself automatically. ::: note Manually add the values for `AUTH0_AUDIENCE` and `AUTH_SCOPE` to the file `lib/auth0.js`. These values are not configured automatically. +If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab. ::: ### Create the Auth0 SDK Client @@ -121,27 +122,27 @@ export const GET = async function shows() { }; ``` -Upon execution the following routes for your customers are available: +Upon execution, the following routes for your customers are available: -- `/auth/login`: The route to perform login with Auth0. -- `/auth/logout`: The route to log the user out. -- `/auth/callback`: The route Auth0 will redirect the user to after a successful login. -- `/auth/profile`: The route to fetch the user profile. -- `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available). -- `/auth/backchannell-logout`: The route to receive a logout_token when a configured Back-Channel Logout initiator occurs. +- `/auth/login`: The route to perform login with Auth0 +- `/auth/logout`: The route to log the user out +- `/auth/callback`: The route Auth0 will redirect the user to after a successful login +- `/auth/profile`: The route to fetch the user profile +- `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available) +- `/auth/backchannell-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs To learn more about routing in Auth0, read Add the dynamic API route. ## Add Login to Your Application -Users can now log in to your application at `/api/auth/login` route provided by the SDK. Use an **anchor tag** to add a link to the login route, the route redirects your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 redirects your users back to your application. +Users can now log in to your application at `/api/auth/login` route provided by the SDK. Use an **anchor tag** to add a link to the login route to redirect your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 redirects your users back to your application. ```html Login ``` :::note -Next suggest using Link components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed. +Next.js suggest using Link components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed. ::: :::panel Checkpoint From 1e2a75a3bd46caea87e2b73daa412a947fa8a084 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 20:42:10 +0200 Subject: [PATCH 06/18] Update index.yml --- articles/quickstart/webapp/nextjs/index.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/index.yml b/articles/quickstart/webapp/nextjs/index.yml index 09ceb743f6..2fc7d9d1fc 100644 --- a/articles/quickstart/webapp/nextjs/index.yml +++ b/articles/quickstart/webapp/nextjs/index.yml @@ -12,7 +12,7 @@ framework: - Next.js author: name: Rita Zerrizuela - email: rita.zerrizuelag@auth0.com + email: rita.zerrizuela@auth0.com community: false topics: From d566fdc2d0b8bcc413001d95e1bc53a943408f4a Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 20:44:28 +0200 Subject: [PATCH 07/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index a57ef2a927..5eeb5f1e47 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -135,7 +135,7 @@ To learn more about routing in Auth0, read Login From b81647b5a039d4e16a0e719db3f6ff5931cfec40 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 20:48:14 +0200 Subject: [PATCH 08/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 5eeb5f1e47..8bfacf22e9 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -122,7 +122,7 @@ export const GET = async function shows() { }; ``` -Upon execution, the following routes for your customers are available: +Upon execution, the following routes are available: - `/auth/login`: The route to perform login with Auth0 - `/auth/logout`: The route to log the user out @@ -142,7 +142,7 @@ Users can now log in to your application at `/auth/login` route provided by the ``` :::note -Next.js suggest using Link components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed. +Next.js suggests using Link components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed. ::: :::panel Checkpoint From 8c7d5f0f55e407461a6878aff8e603cc5f25b3f1 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Mon, 31 Mar 2025 20:55:45 +0200 Subject: [PATCH 09/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 8bfacf22e9..b8b1f0f9d7 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -53,7 +53,7 @@ The SDK will read these values from the Node.js process environment and configur ::: note Manually add the values for `AUTH0_AUDIENCE` and `AUTH_SCOPE` to the file `lib/auth0.js`. These values are not configured automatically. -If you are using a Custom Domain with Auth0, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab. +If you are using a Custom Domain with Auth0, set `AUTH0_DOMAIN` to the value of your Custom Domain instead of the value reflected in the application "Settings" tab. ::: ### Create the Auth0 SDK Client @@ -129,7 +129,7 @@ Upon execution, the following routes are available: - `/auth/callback`: The route Auth0 will redirect the user to after a successful login - `/auth/profile`: The route to fetch the user profile - `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available) -- `/auth/backchannell-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs +- `/auth/backchannel-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs To learn more about routing in Auth0, read Add the dynamic API route. From 1120ad584a0a2e838dd8c4a38f5bcf886017bf8d Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Tue, 1 Apr 2025 10:47:50 +0200 Subject: [PATCH 10/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index b8b1f0f9d7..f83c6dce64 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -128,11 +128,14 @@ Upon execution, the following routes are available: - `/auth/logout`: The route to log the user out - `/auth/callback`: The route Auth0 will redirect the user to after a successful login - `/auth/profile`: The route to fetch the user profile -- `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available) +- `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available) - `/auth/backchannel-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs To learn more about routing in Auth0, read Add the dynamic API route. +:::note +The `/auth/access-token` route is enabled by default. If your clients do not need access tokens, you can disable the route by editing the file `lib/auth0.js` and adding `enableAccessTokenEndpoint = false` to the instance of the Auth0 client. ::: + ## Add Login to Your Application Users can now log in to your application at `/auth/login` route provided by the SDK. Use an **anchor tag** to add a link to the login route to redirect your users to the Auth0 Universal Login Page, where Auth0 can authenticate them. Upon successful authentication, Auth0 redirects your users back to your application. From aed26eb8ec2a7aaf68ef0bf32980f96163f7700d Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Tue, 1 Apr 2025 11:10:38 +0200 Subject: [PATCH 11/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index f83c6dce64..c0373a23bb 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -134,7 +134,7 @@ Upon execution, the following routes are available: To learn more about routing in Auth0, read Add the dynamic API route. :::note -The `/auth/access-token` route is enabled by default. If your clients do not need access tokens, you can disable the route by editing the file `lib/auth0.js` and adding `enableAccessTokenEndpoint = false` to the instance of the Auth0 client. ::: +The `/auth/access-token` route is enabled by default. If your clients do not need access tokens, you can disable the route by editing the file `lib/auth0.js` and setting `enableAccessTokenEndpoint` to `false` in the instance of the Auth0 client. ::: ## Add Login to Your Application From 8923fcc138e35036e81f614ac9f370efa4e6a448 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Wed, 2 Apr 2025 09:59:57 +0200 Subject: [PATCH 12/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index c0373a23bb..b56b60dfba 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -200,32 +200,25 @@ export default function Profile() { {isLoading && } {user && ( <> - - + {isLoading &&

Loading...

} + {user && ( +
Profile - -

{user.name}

-

- {user.email} -

- - - - {JSON.stringify(user, null, 2)} - +

{user.email}

+
{JSON.stringify(user, null, 2)}
+
+ )} )} ); } - ``` The `user` property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors: From 04c8532e8c65e61cfd73482373fca278da1ada45 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Wed, 2 Apr 2025 10:12:20 +0200 Subject: [PATCH 13/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 79 +++++++++---------- 1 file changed, 39 insertions(+), 40 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index b56b60dfba..309df12111 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -84,45 +84,7 @@ export const auth0 = new Auth0Client({ }); ``` - -### Add the dynamic API route handler - -Create a file at `app/api/shows/route.js`. This is your route Handler file using Dynamic Route Segment. The file declares a `GET` export to call the `shows()` method from the SDK to create the API routes. import the `handleAuth` method from the SDK and call it from the `GET` export. - -```javascript -// app/api/shows/route.js -import { NextResponse } from 'next/server'; -import { auth0 } from '../../../lib/auth0'; - -export const GET = async function shows() { - try { - const session = await auth0.getSession(); - - if (!session) { - return NextResponse.json( - { error: 'Not authenticated' }, - { status: 401 } - ); - } - - const res = new NextResponse(); - const { token: accessToken } = await auth0.getAccessToken(); - const apiPort = process.env.API_PORT || 3001; - const response = await fetch(`http://localhost:${apiPort}/api/shows`, { - headers: { - Authorization: `Bearer ${accessToken}` - } - }); - const shows = await response.json(); - - return NextResponse.json(shows, res); - } catch (error) { - return NextResponse.json({ error: error.message }, { status: error.status || 500 }); - } -}; -``` - -Upon execution, the following routes are available: +The SDK auto-configures the following routes: - `/auth/login`: The route to perform login with Auth0 - `/auth/logout`: The route to log the user out @@ -243,7 +205,44 @@ export default async function ProfileServer() { :::panel Checkpoint Verify that you can display the `user.name` or any other `user` property within a component correctly after you have logged in. -::: +::: + +### Create custom routes using the dynamic API route handler + +Create the file at `app/api/shows/route.js`. This is your route Handler file using Dynamic Route Segment. The file declares a `GET` export to call the `shows()` method from the SDK to create custom API routes. import the `handleAuth` method from the SDK and call it from the `GET` export. + +```javascript +// app/api/shows/route.js +import { NextResponse } from 'next/server'; +import { auth0 } from '../../../lib/auth0'; + +export const GET = async function shows() { + try { + const session = await auth0.getSession(); + + if (!session) { + return NextResponse.json( + { error: 'Not authenticated' }, + { status: 401 } + ); + } + + const res = new NextResponse(); + const { token: accessToken } = await auth0.getAccessToken(); + const apiPort = process.env.API_PORT || 3001; + const response = await fetch(`http://localhost:${apiPort}/api/shows`, { + headers: { + Authorization: `Bearer ${accessToken}` + } + }); + const shows = await response.json(); + + return NextResponse.json(shows, res); + } catch (error) { + return NextResponse.json({ error: error.message }, { status: error.status || 500 }); + } +}; +``` ## What's next? From ec96954d50b72b08455982a328ae906e7bb1aaa1 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Wed, 2 Apr 2025 10:31:53 +0200 Subject: [PATCH 14/18] Update 01-login.md --- articles/quickstart/webapp/nextjs/01-login.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 309df12111..1dfb8f85b4 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -149,11 +149,6 @@ The profile information is available through the `user` property exposed by the ```jsx 'use client'; -import React from 'react'; -import { Row, Col } from 'reactstrap'; -import { useUser } from '@auth0/nextjs-auth0'; -import Loading from '../../components/Loading'; -import Highlight from '../../components/Highlight'; export default function Profile() { const { user, isLoading } = useUser(); From 0fe52d3683e63bb2cd0e6ed1583f5667cb71b2e5 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 7 Apr 2025 11:50:32 +0200 Subject: [PATCH 15/18] Address review comments --- articles/quickstart/webapp/nextjs/01-login.md | 32 +++++++------------ 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 1dfb8f85b4..8958a2a997 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -93,10 +93,8 @@ The SDK auto-configures the following routes: - `/auth/access-token`: The route to verify the user's session and return an access token (which automatically refreshes if a refresh token is available) - `/auth/backchannel-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs -To learn more about routing in Auth0, read Add the dynamic API route. - :::note -The `/auth/access-token` route is enabled by default. If your clients do not need access tokens, you can disable the route by editing the file `lib/auth0.js` and setting `enableAccessTokenEndpoint` to `false` in the instance of the Auth0 client. ::: +The `/auth/access-token` route is enabled by default, but is only neccessary when the access token is needed on the client-side. If this isn't something you need, you can disable this endpoint by setting `enableAccessTokenEndpoint` to `false`. ::: ## Add Login to Your Application @@ -154,24 +152,18 @@ export default function Profile() { const { user, isLoading } = useUser(); return ( <> - {isLoading && } + {isLoading &&

Loading...

} {user && ( - <> - {isLoading &&

Loading...

} - {user && ( -
- Profile -

{user.name}

-

{user.email}

-
{JSON.stringify(user, null, 2)}
-
- )} - +
+ Profile +

{user.name}

+

{user.email}

+
{JSON.stringify(user, null, 2)}
+
)} ); From b8fa6966f465ed4923bc42b1a6fdaa6169af0800 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 7 Apr 2025 12:20:19 +0200 Subject: [PATCH 16/18] Fix incorrectly rendered note block --- articles/quickstart/webapp/nextjs/01-login.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 8958a2a997..6516981e03 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -94,7 +94,8 @@ The SDK auto-configures the following routes: - `/auth/backchannel-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs :::note -The `/auth/access-token` route is enabled by default, but is only neccessary when the access token is needed on the client-side. If this isn't something you need, you can disable this endpoint by setting `enableAccessTokenEndpoint` to `false`. ::: +The `/auth/access-token` route is enabled by default, but is only neccessary when the access token is needed on the client-side. If this isn't something you need, you can disable this endpoint by setting `enableAccessTokenEndpoint` to `false`. +::: ## Add Login to Your Application From e2e155646d23da934bf69c767003e8234e3f0e1f Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 7 Apr 2025 12:21:27 +0200 Subject: [PATCH 17/18] Delete API route handler section as it breaks compilation --- articles/quickstart/webapp/nextjs/01-login.md | 37 ------------------- 1 file changed, 37 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 6516981e03..83cb4ac8fc 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -195,43 +195,6 @@ export default async function ProfileServer() { Verify that you can display the `user.name` or any other `user` property within a component correctly after you have logged in. ::: -### Create custom routes using the dynamic API route handler - -Create the file at `app/api/shows/route.js`. This is your route Handler file using Dynamic Route Segment. The file declares a `GET` export to call the `shows()` method from the SDK to create custom API routes. import the `handleAuth` method from the SDK and call it from the `GET` export. - -```javascript -// app/api/shows/route.js -import { NextResponse } from 'next/server'; -import { auth0 } from '../../../lib/auth0'; - -export const GET = async function shows() { - try { - const session = await auth0.getSession(); - - if (!session) { - return NextResponse.json( - { error: 'Not authenticated' }, - { status: 401 } - ); - } - - const res = new NextResponse(); - const { token: accessToken } = await auth0.getAccessToken(); - const apiPort = process.env.API_PORT || 3001; - const response = await fetch(`http://localhost:${apiPort}/api/shows`, { - headers: { - Authorization: `Bearer ${accessToken}` - } - }); - const shows = await response.json(); - - return NextResponse.json(shows, res); - } catch (error) { - return NextResponse.json({ error: error.message }, { status: error.status || 500 }); - } -}; -``` - ## What's next? We put together a few examples on how to use nextjs-auth0 for more advanced use cases. From abcca14dd5e345b8506b06ca496834578a4af7b2 Mon Sep 17 00:00:00 2001 From: Frederik Prijck Date: Mon, 7 Apr 2025 12:39:28 +0200 Subject: [PATCH 18/18] Add middleware section --- articles/quickstart/webapp/nextjs/01-login.md | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/01-login.md b/articles/quickstart/webapp/nextjs/01-login.md index 83cb4ac8fc..74d19680bc 100644 --- a/articles/quickstart/webapp/nextjs/01-login.md +++ b/articles/quickstart/webapp/nextjs/01-login.md @@ -84,7 +84,37 @@ export const auth0 = new Auth0Client({ }); ``` -The SDK auto-configures the following routes: +### Add the Authentication Middleware + +The Next.js Middleware allows you to run code before a request is completed. +Create a `middleware.ts` file. This file is used to enforce authentication on specific routes. + +```javascript +import type { NextRequest } from "next/server"; +import { auth0 } from "./lib/auth0"; + +export async function middleware(request: NextRequest) { + return await auth0.middleware(request); +} + +export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - _next/static (static files) + * - _next/image (image optimization files) + * - favicon.ico, sitemap.xml, robots.txt (metadata files) + */ + "/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", + ], +}; +``` + +The `middleware` function intercepts incoming requests and applies Auth0's authentication logic. The `matcher` configuration ensures that the middleware runs on all routes except for static files and metadata. + +#### Auto-configured routes + +Using the SDK's middleware auto-configures the following routes: - `/auth/login`: The route to perform login with Auth0 - `/auth/logout`: The route to log the user out