Skip to content

Commit 8d82e52

Browse files
Update nextjs non-interactive quickstart for v4 (#10520)
* Update download.md Edited Callback URL path * Update index.yml Updated author and Next.js requirements * Update index.yml reverted author info * Update 01-login.md Updated Quickstart from V3 -> V4. * Update 01-login.md * Update index.yml * Update 01-login.md * Update 01-login.md * Update 01-login.md * Update 01-login.md * Update 01-login.md * Update 01-login.md * Update 01-login.md * Update 01-login.md * Address review comments * Fix incorrectly rendered note block * Delete API route handler section as it breaks compilation * Add middleware section --------- Co-authored-by: Frederik Prijck <[email protected]>
1 parent a9d4fa6 commit 8d82e52

File tree

3 files changed

+114
-90
lines changed

3 files changed

+114
-90
lines changed

articles/quickstart/webapp/nextjs/01-login.md

+112-88
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ useCase: quickstart
1414
---
1515
<!-- markdownlint-disable MD002 MD034 MD041 -->
1616

17-
<%= include('../_includes/_getting_started', { library: 'Next.js', callback: 'http://localhost:3000/api/auth/callback' }) %>
17+
<%= include('../_includes/_getting_started', { library: 'Next.js', callback: 'http://localhost:3000/auth/callback' }) %>
1818

1919
<%= include('../../../_includes/_logout_url', { returnTo: 'http://localhost:3000' }) %>
2020

@@ -23,98 +23,133 @@ useCase: quickstart
2323
Run the following command within your project directory to install the Auth0 Next.js SDK:
2424

2525
```sh
26-
npm install @auth0/nextjs-auth0@3
26+
npm install @auth0/nextjs-auth0
2727
```
2828

2929
The SDK exposes methods and variables that help you integrate Auth0 with your Next.js application using <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers" target="_blank" rel="noreferrer">Route Handlers</a> on the backend and <a href="https://react.dev/reference/react/useContext" target="_blank" rel="noreferrer">React Context</a> with <a href="https://react.dev/reference/react/hooks" target="_blank" rel="noreferrer">React Hooks</a> on the frontend.
3030

3131
### Configure the SDK
3232

33-
In the root directory of your project, add the file `.env.local` with the following <a href="https://nextjs.org/docs/basic-features/environment-variables" target="_blank" rel="noreferrer">environment variables</a>:
33+
In the root directory of your project, create the file `.env.local` with the following <a href="https://nextjs.org/docs/basic-features/environment-variables" target="_blank" rel="noreferrer">environment variables</a>:
3434

3535
```sh
3636
AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
37-
AUTH0_BASE_URL='http://localhost:3000'
38-
AUTH0_ISSUER_BASE_URL='https://${account.namespace}'
37+
APP_BASE_URL='http://localhost:3000'
38+
AUTH0_DOMAIN='https://${account.namespace}'
3939
AUTH0_CLIENT_ID='${account.clientId}'
4040
AUTH0_CLIENT_SECRET='${account.clientSecret}'
41+
'If your application is API authorized add the variables AUTH0_AUDIENCE and AUTH0_SCOPE'
42+
AUTH0_AUDIENCE='your_auth_api_identifier'
43+
AUTH0_SCOPE='openid profile email read:shows'
4144
```
4245

4346
- `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.
44-
- `AUTH0_BASE_URL`: The base URL of your application.
45-
- `AUTH0_ISSUER_BASE_URL`: The URL of your Auth0 tenant domain. If you are using a <a href="https://auth0.com/docs/custom-domains" target="_blank" rel="noreferrer">Custom Domain with Auth0</a>, set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab.
46-
- `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID.
47-
- `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret.
47+
- `APP_BASE_URL`: The base URL of your application
48+
- `AUTH0_DOMAIN`: The URL of your Auth0 tenant domain
49+
- `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID
50+
- `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret
4851

49-
The SDK will read these values from the Node.js process environment and automatically configure itself.
52+
The SDK will read these values from the Node.js process environment and configure itself automatically.
5053

51-
### Add the dynamic API route handler
54+
::: note
55+
Manually add the values for `AUTH0_AUDIENCE` and `AUTH_SCOPE` to the file `lib/auth0.js`. These values are not configured automatically.
56+
If you are using a <a href="https://auth0.com/docs/custom-domains" target="_blank" rel="noreferrer">Custom Domain with Auth0</a>, set `AUTH0_DOMAIN` to the value of your Custom Domain instead of the value reflected in the application "Settings" tab.
57+
:::
5258

53-
Create a file at `app/api/auth/[auth0]/route.js`. This is your Route Handler file with a <a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments" target="_blank" rel="noreferrer">Dynamic Route Segment</a>.
59+
### Create the Auth0 SDK Client
5460

55-
Then, import the `handleAuth` method from the SDK and call it from the `GET` export.
61+
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.
5662

5763
```javascript
58-
// app/api/auth/[auth0]/route.js
59-
import { handleAuth } from '@auth0/nextjs-auth0';
60-
61-
export const GET = handleAuth();
64+
// lib/auth0.js
65+
66+
import { Auth0Client } from "@auth0/nextjs-auth0/server";
67+
68+
// Initialize the Auth0 client
69+
export const auth0 = new Auth0Client({
70+
// Options are loaded from environment variables by default
71+
// Ensure necessary environment variables are properly set
72+
// domain: process.env.AUTH0_DOMAIN,
73+
// clientId: process.env.AUTH0_CLIENT_ID,
74+
// clientSecret: process.env.AUTH0_CLIENT_SECRET,
75+
// appBaseUrl: process.env.APP_BASE_URL,
76+
// secret: process.env.AUTH0_SECRET,
77+
78+
authorizationParameters: {
79+
// In v4, the AUTH0_SCOPE and AUTH0_AUDIENCE environment variables for API authorized applications are no longer automatically picked up by the SDK.
80+
// Instead, we need to provide the values explicitly.
81+
scope: process.env.AUTH0_SCOPE,
82+
audience: process.env.AUTH0_AUDIENCE,
83+
}
84+
});
6285
```
6386

64-
This creates the following routes:
87+
### Add the Authentication Middleware
6588

66-
- `/api/auth/login`: The route used to perform login with Auth0.
67-
- `/api/auth/logout`: The route used to log the user out.
68-
- `/api/auth/callback`: The route Auth0 will redirect the user to after a successful login.
69-
- `/api/auth/me`: The route to fetch the user profile from.
89+
The Next.js Middleware allows you to run code before a request is completed.
90+
Create a `middleware.ts` file. This file is used to enforce authentication on specific routes.
7091

71-
::: note
72-
This QuickStart targets the Next.js <a href="https://nextjs.org/docs/app" target="_blank" rel="noreferrer">App Router</a>. If you're using the <a href="https://nextjs.org/docs/pages" target="_blank" rel="noreferrer">Pages Router</a>, check out the example in the SDK's <a href="https://github.com/auth0/nextjs-auth0#page-router" target="_blank" rel="noreferrer">README</a>.
73-
:::
92+
```javascript
93+
import type { NextRequest } from "next/server";
94+
import { auth0 } from "./lib/auth0";
7495

75-
### Add the `UserProvider` component
96+
export async function middleware(request: NextRequest) {
97+
return await auth0.middleware(request);
98+
}
7699

77-
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 <a href="https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required" target="_blank" rel="noreferrer">Root Layout component</a> and wrap the `<body>` tag with a `UserProvider` in the file `app/layout.jsx`.
100+
export const config = {
101+
matcher: [
102+
/*
103+
* Match all request paths except for the ones starting with:
104+
* - _next/static (static files)
105+
* - _next/image (image optimization files)
106+
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
107+
*/
108+
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
109+
],
110+
};
111+
```
78112

79-
Create the file `app/layout.jsx` as follows:
113+
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.
80114

81-
```jsx
82-
// app/layout.jsx
83-
import { UserProvider } from '@auth0/nextjs-auth0/client';
115+
#### Auto-configured routes
84116

85-
export default function RootLayout({ children }) {
86-
return (
87-
<html lang="en">
88-
<UserProvider>
89-
<body>{children}</body>
90-
</UserProvider>
91-
</html>
92-
);
93-
}
94-
```
117+
Using the SDK's middleware auto-configures the following routes:
95118

96-
The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook.
119+
- `/auth/login`: The route to perform login with Auth0
120+
- `/auth/logout`: The route to log the user out
121+
- `/auth/callback`: The route Auth0 will redirect the user to after a successful login
122+
- `/auth/profile`: The route to fetch the user profile
123+
- `/auth/access-token`: The route to verify the user's session and return an <a href="https://auth0.com/docs/secure/tokens/access-tokens" target="_blank" rel="noreferrer">access token</a> (which automatically refreshes if a refresh token is available)
124+
- `/auth/backchannel-logout`: The route to receive a `logout_token` when a configured Back-Channel Logout initiator occurs
97125

98-
:::panel Checkpoint
99-
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.
126+
:::note
127+
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`.
100128
:::
101129

102130
## Add Login to Your Application
103131

104-
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.
105-
106-
:::note
107-
Next linting rules might suggest using the `Link` component instead of an anchor tag. The `Link` component is meant to perform <a href="https://nextjs.org/docs/api-reference/next/link" target="_blank" rel="noreferrer">client-side transitions between pages</a>. As the link points to an API route and not to a page, you should keep it as an anchor tag.
108-
:::
132+
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.
109133

110134
```html
111-
<a href="/api/auth/login">Login</a>
135+
<a href="/auth/login">Login</a>
112136
```
113137

138+
:::note
139+
Next.js suggests using <a href="https://nextjs.org/docs/api-reference/next/link" target="_blank" rel="noreferrer">Link</a> components instead of anchor tags, but since these are API routes and not pages, anchor tags are needed.
140+
:::
141+
114142
:::panel Checkpoint
115-
Add the login link to your application. When you click it, verify that your Next.js application redirects you to the <a href="https://auth0.com/universal-login" target="_blank" rel="noreferrer">Auth0 Universal Login</a> page and that you can now log in or sign up using a username and password or a social provider.
143+
Add the login link to your application. Select it and verify that your Next.js application redirects you to the <a href="https://auth0.com/universal-login" target="_blank" rel="noreferrer">Auth0 Universal Login</a> page and that you can now log in or sign up using a username and password or a social provider.
116144

117145
Once that's complete, verify that Auth0 redirects back to your application.
146+
147+
If you are following along with the sample app project from the top of this page, run the command:
148+
149+
```sh
150+
npm i && npm run dev
151+
```
152+
and visit http://localhost:3000 in your browser.
118153
:::
119154

120155
![Auth0 Universal Login](/media/quickstarts/universal-login.png)
@@ -123,14 +158,14 @@ Once that's complete, verify that Auth0 redirects back to your application.
123158

124159
## Add Logout to Your Application
125160

126-
Now that you can log in to your Next.js application, you need <a href="https://auth0.com/docs/logout/log-users-out-of-auth0" target="_blank" rel="noreferrer">a way to log out</a>. Add a link that points to the `/api/auth/logout` API route. Clicking it redirects your users to your <a href="https://auth0.com/docs/api/authentication?javascript#logout" target="_blank" rel="noreferrer">Auth0 logout endpoint</a> (`https://YOUR_DOMAIN/v2/logout`) and then immediately redirects them back to your application.
161+
Now that you can log in to your Next.js application, you need <a href="https://auth0.com/docs/logout/log-users-out-of-auth0" target="_blank" rel="noreferrer">a way to log out</a>. Add a link that points to the `/auth/logout` API route. To learn more, read <a href="https://auth0.com/docs/authenticate/login/logout/log-users-out-of-auth0" target="_blank" rel="noreferrer">Log Users out of Auth0 with OIDC Endpoint</a>.
127162

128163
```html
129-
<a href="/api/auth/logout">Logout</a>
164+
<a href="/auth/logout">Logout</a>
130165
```
131166

132167
:::panel Checkpoint
133-
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".
168+
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".
134169
:::
135170

136171
## Show User Profile Information
@@ -144,22 +179,24 @@ The profile information is available through the `user` property exposed by the
144179
```jsx
145180
'use client';
146181

147-
import { useUser } from '@auth0/nextjs-auth0/client';
148-
149-
export default function ProfileClient() {
150-
const { user, error, isLoading } = useUser();
151-
152-
if (isLoading) return <div>Loading...</div>;
153-
if (error) return <div>{error.message}</div>;
154-
182+
export default function Profile() {
183+
const { user, isLoading } = useUser();
155184
return (
156-
user && (
157-
<div>
158-
<img src={user.picture} alt={user.name} />
159-
<h2>{user.name}</h2>
160-
<p>{user.email}</p>
161-
</div>
162-
)
185+
<>
186+
{isLoading && <p>Loading...</p>}
187+
{user && (
188+
<div style={{ textAlign: "center" }}>
189+
<img
190+
src={user.picture}
191+
alt="Profile"
192+
style={{ borderRadius: "50%", width: "80px", height: "80px" }}
193+
/>
194+
<h2>{user.name}</h2>
195+
<p>{user.email}</p>
196+
<pre>{JSON.stringify(user, null, 2)}</pre>
197+
</div>
198+
)}
199+
</>
163200
);
164201
}
165202
```
@@ -175,32 +212,19 @@ The `user` property contains sensitive information and artifacts related to the
175212
The profile information is available through the `user` property exposed by the `getSession` function. Take this <a href="https://nextjs.org/docs/getting-started/react-essentials#server-components" target="_blank" rel="noreferrer">Server Component</a> as an example of how to use it:
176213

177214
```jsx
178-
import { getSession } from '@auth0/nextjs-auth0';
215+
import { auth0 } from "@/lib/auth0";
179216

180217
export default async function ProfileServer() {
181-
const { user } = await getSession();
182-
183-
return (
184-
user && (
185-
<div>
186-
<img src={user.picture} alt={user.name} />
187-
<h2>{user.name}</h2>
188-
<p>{user.email}</p>
189-
</div>
190-
)
191-
);
218+
const { user } = await auth0.getSession();
219+
return ( user && ( <div> <img src={user.picture} alt={user.name}/> <h2>{user.name}</h2> <p>{user.email}</p> </div> ) );
192220
}
221+
193222
```
194223

195224
:::panel Checkpoint
196225
Verify that you can display the `user.name` or <a href="https://auth0.com/docs/users/user-profile-structure#user-profile-attributes" target="_blank" rel="noreferrer">any other</a> `user` property within a component correctly after you have logged in.
197-
:::
226+
:::
198227

199228
## What's next?
200229

201-
We put together a few examples of how to use <a href="https://github.com/auth0/nextjs-auth0" target="_blank" rel="noreferrer">nextjs-auth0</a> in more advanced use cases:
202-
203-
- <a href="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#protecting-a-server-side-rendered-ssr-page" target="_blank" rel="noreferrer">Protecting a Server Side Rendered (SSR) Page</a>
204-
- <a href="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#protecting-a-client-side-rendered-csr-page" target="_blank" rel="noreferrer">Protecting a Client Side Rendered (CSR) Page</a>
205-
- <a href="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#protect-an-api-route" target="_blank" rel="noreferrer">Protect an API Route</a>
206-
- <a href="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#access-an-external-api-from-an-api-route" target="_blank" rel="noreferrer">Access an External API from an API Route</a>
230+
We put together a few <a href="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md" target="_blank" rel="noreferrer">examples</a> on how to use <a href="https://github.com/auth0/nextjs-auth0" target="_blank" rel="noreferrer">nextjs-auth0</a> for more advanced use cases.

articles/quickstart/webapp/nextjs/download.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ To run the sample follow these steps:
44

55
1) Set the **Allowed Callback URLs** in the <a href="${manage_url}/#/applications/${account.clientId}/settings" target="_blank" rel="noreferrer">Application Settings</a> to
66
```text
7-
http://localhost:3000/api/auth/callback
7+
http://localhost:3000/auth/callback
88
```
99

1010
2) Set **Allowed Logout URLs** in the <a href="${manage_url}/#/applications/${account.clientId}/settings" target="_blank" rel="noreferrer">Application Settings</a> to

articles/quickstart/webapp/nextjs/index.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ seo_alias: nextjs
2323
show_releases: true
2424
show_steps: true
2525
requirements:
26-
- Next.js 13.4+
26+
- Next.js 15.2.4+
2727
default_article: 01-login
2828
articles:
2929
- 01-login

0 commit comments

Comments
 (0)