You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Run the following command within your project directory to install the Auth0 Next.js SDK:
24
24
25
25
```sh
26
-
npm install @auth0/nextjs-auth0@3
26
+
npm install @auth0/nextjs-auth0
27
27
```
28
28
29
29
The SDK exposes methods and variables that help you integrate Auth0 with your Next.js application using <ahref="https://nextjs.org/docs/app/building-your-application/routing/route-handlers"target="_blank"rel="noreferrer">Route Handlers</a> on the backend and <ahref="https://react.dev/reference/react/useContext"target="_blank"rel="noreferrer">React Context</a> with <ahref="https://react.dev/reference/react/hooks"target="_blank"rel="noreferrer">React Hooks</a> on the frontend.
30
30
31
31
### Configure the SDK
32
32
33
-
In the root directory of your project, add the file `.env.local` with the following <ahref="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 <ahref="https://nextjs.org/docs/basic-features/environment-variables"target="_blank"rel="noreferrer">environment variables</a>:
34
34
35
35
```sh
36
36
AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
'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'
41
44
```
42
45
43
46
-`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 <ahref="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
48
51
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.
50
53
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 <ahref="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
+
:::
52
58
53
-
Create a file at `app/api/auth/[auth0]/route.js`. This is your Route Handler file with a <ahref="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
54
60
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.
// 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
+
});
62
85
```
63
86
64
-
This creates the following routes:
87
+
### Add the Authentication Middleware
65
88
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.
70
91
71
-
::: note
72
-
This QuickStart targets the Next.js <ahref="https://nextjs.org/docs/app"target="_blank"rel="noreferrer">App Router</a>. If you're using the <ahref="https://nextjs.org/docs/pages"target="_blank"rel="noreferrer">Pages Router</a>, check out the example in the SDK's <ahref="https://github.com/auth0/nextjs-auth0#page-router"target="_blank"rel="noreferrer">README</a>.
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 <ahref="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
+
exportconstconfig= {
101
+
matcher: [
102
+
/*
103
+
* Match all request paths except for the ones starting with:
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.
Using the SDK's middleware auto-configures the following routes:
95
118
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 <ahref="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
97
125
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`.
100
128
:::
101
129
102
130
## Add Login to Your Application
103
131
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 <ahref="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.
109
133
110
134
```html
111
-
<ahref="/api/auth/login">Login</a>
135
+
<ahref="/auth/login">Login</a>
112
136
```
113
137
138
+
:::note
139
+
Next.js suggests using <ahref="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
+
114
142
:::panel Checkpoint
115
-
Add the login link to your application. When you click it, verify that your Next.js application redirects you to the <ahref="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 <ahref="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.
116
144
117
145
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:
@@ -123,14 +158,14 @@ Once that's complete, verify that Auth0 redirects back to your application.
123
158
124
159
## Add Logout to Your Application
125
160
126
-
Now that you can log in to your Next.js application, you need <ahref="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 <ahref="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 <ahref="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 <ahref="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>.
127
162
128
163
```html
129
-
<ahref="/api/auth/logout">Logout</a>
164
+
<ahref="/auth/logout">Logout</a>
130
165
```
131
166
132
167
:::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".
134
169
:::
135
170
136
171
## Show User Profile Information
@@ -144,22 +179,24 @@ The profile information is available through the `user` property exposed by the
@@ -175,32 +212,19 @@ The `user` property contains sensitive information and artifacts related to the
175
212
The profile information is available through the `user` property exposed by the `getSession` function. Take this <ahref="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:
176
213
177
214
```jsx
178
-
import { getSession } from'@auth0/nextjs-auth0';
215
+
import { auth0 } from"@/lib/auth0";
179
216
180
217
exportdefaultasyncfunctionProfileServer() {
181
-
const { user } =awaitgetSession();
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 } =awaitauth0.getSession();
219
+
return ( user && ( <div><img src={user.picture} alt={user.name}/><h2>{user.name}</h2><p>{user.email}</p></div> ) );
192
220
}
221
+
193
222
```
194
223
195
224
:::panel Checkpoint
196
225
Verify that you can display the `user.name` or <ahref="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
+
:::
198
227
199
228
## What's next?
200
229
201
-
We put together a few examples of how to use <ahref="https://github.com/auth0/nextjs-auth0"target="_blank"rel="noreferrer">nextjs-auth0</a> in more advanced use cases:
202
-
203
-
- <ahref="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
-
- <ahref="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
-
- <ahref="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#protect-an-api-route"target="_blank"rel="noreferrer">Protect an API Route</a>
206
-
- <ahref="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 <ahref="https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md"target="_blank"rel="noreferrer">examples</a> on how to use <ahref="https://github.com/auth0/nextjs-auth0"target="_blank"rel="noreferrer">nextjs-auth0</a> for more advanced use cases.
Copy file name to clipboardExpand all lines: articles/quickstart/webapp/nextjs/download.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ To run the sample follow these steps:
4
4
5
5
1) Set the **Allowed Callback URLs** in the <ahref="${manage_url}/#/applications/${account.clientId}/settings"target="_blank"rel="noreferrer">Application Settings</a> to
6
6
```text
7
-
http://localhost:3000/api/auth/callback
7
+
http://localhost:3000/auth/callback
8
8
```
9
9
10
10
2) Set **Allowed Logout URLs** in the <ahref="${manage_url}/#/applications/${account.clientId}/settings"target="_blank"rel="noreferrer">Application Settings</a> to
0 commit comments