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
description: This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js SDK.
3
+
description: This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js v4 SDK (Beta).
4
4
topics:
5
5
- quickstarts
6
6
- webapp
@@ -12,32 +12,30 @@ contentType: tutorial
12
12
useCase: quickstart
13
13
interactive: true
14
14
files:
15
-
- files/auth
15
+
- files/auth0
16
16
- files/env
17
-
- files/layout
18
-
- files/login
19
-
- files/logout
20
-
- files/profile-client
21
-
- files/profile-server
17
+
- files/middleware
18
+
- files/page
19
+
22
20
---
23
21
24
22
<!-- markdownlint-disable MD025 MD034 -->
25
23
26
24
# Add Login to Your Next.js Application
27
25
28
-
This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js SDK. We recommend that you log in to follow this quickstart with examples configured for your account.
26
+
This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js v4 SDK (Beta). We recommend that you log in to follow this quickstart with examples configured for your account.
Run the following command within your project directory to install the Auth0 Next.js SDK:
38
36
39
37
```sh
40
-
npm install @auth0/nextjs-auth0
38
+
npm install @auth0/nextjs-auth0@beta
41
39
```
42
40
43
41
The SDK exposes methods and variables that help you integrate Auth0 with your Next.js application using [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) on the backend and [React Context](https://reactjs.org/docs/context.html) with [React Hooks](https://reactjs.org/docs/hooks-overview.html) on the frontend.
@@ -47,60 +45,62 @@ The SDK exposes methods and variables that help you integrate Auth0 with your Ne
47
45
In the root directory of your project, add the file `.env.local` with the following [environment variables](https://nextjs.org/docs/basic-features/environment-variables):
48
46
49
47
-`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.
50
-
-`AUTH0_BASE_URL`: The base URL of your application.
51
-
-`AUTH0_ISSUER_BASE_URL`: The URL of your Auth0 tenant domain. If you are using a [Custom Domain with Auth0](https://auth0.com/docs/custom-domains), set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab.
48
+
-`APP_BASE_URL`: The base URL of your application.
49
+
-`AUTH0_DOMAIN`: The URL of your Auth0 tenant domain. If you are using a [Custom Domain with Auth0](https://auth0.com/docs/custom-domains), set this to the value of your Custom Domain instead of the value reflected in the "Settings" tab.
52
50
-`AUTH0_CLIENT_ID`: Your Auth0 application's Client ID.
53
51
-`AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret.
54
52
55
53
The SDK will read these values from the Node.js process environment and automatically configure itself.
56
54
57
-
## Add the dynamic Route Handler {{{ data-action=code data-code="app/api/auth/[auth0]/route.js" }}}
55
+
## Create the Auth0 SDK Client {{{ data-action=code data-code="src/lib/auth0.ts" }}}
56
+
57
+
Create a file at `src/lib.auth0.ts`. This file provides methods for handling authentication, sessions and user data.
58
+
59
+
Then, import the `Auth0Client` class from the SDK to create an instance and export it as `auth0`. This instance is used in your app to interact with Auth0.
60
+
61
+
## Add the Authentication Middleware {{{ data-action=code data-code="src/middleware.ts" }}}
58
62
59
63
::: note
60
-
This QuickStart targets the Next.js [App Router](https://nextjs.org/docs/app). If you're using the [Pages Router](https://nextjs.org/docs/pages), check out the example in the SDK's [README](https://github.com/auth0/nextjs-auth0#page-router).
64
+
The Next.js Middleware allows you to run code before a request is completed.
61
65
:::
62
66
63
-
Create a file at `app/api/auth/[auth0]/route.js`. This is your Route Handler file with a [Dynamic Route Segment](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments).
67
+
Create a file at `src/middleware.ts`. This file is used to enforce authentication on specific routes.
64
68
65
-
Then, import the `handleAuth` method from the SDK and call it from the `GET` export. This creates the following routes:
69
+
The `middleware` function intercepts incoming requests and applies Auth0's authentication logic.
70
+
The `matcher` configuration ensures that the middleware runs on all routes except for statis files and metadata.
66
71
67
-
-`/api/auth/login`: The route used to perform login with Auth0.
68
-
-`/api/auth/logout`: The route used to log the user out.
69
-
-`/api/auth/callback`: The route Auth0 will redirect the user to after a successful login.
70
-
-`/api/auth/me`: The route to fetch the user profile from.
72
+
## Add the Landing Page Content {{{ data-action=code data-code="src/app/page.tsx" }}}
71
73
72
-
## Add the `UserProvider` component {{{ data-action=code data-code="app/layout.jsx" }}}
74
+
The Landing page `src/app/page.tsx` is where users interact with your app. It displays different content based on whether the users is logged in or not.
73
75
74
-
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](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required) and wrap the `<body>` tag with a `UserProvider` in the file `app/layout.jsx`.
76
+
Edit the file `src/app/page.tsx`to add the `auht0.getSession()` method to determine if the user is logged in by retrieving the user session.
75
77
76
-
The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook.
78
+
If there is no user session, the method returns `null` and the app displays the **Sign up** or **Log in** buttons.
79
+
If a user sessions exists, the app displays a welcome message with the user's name and a **Log out** button.
77
80
78
-
::::checkpoint
79
-
:::checkpoint-default
80
-
Now that you have added the route handler and `UserProvider`, run your application to verify that your application is not throwing any errors related to Auth0.
81
+
::: note
82
+
The Logout functionality is already included in the file `src/app/page.tsx`.
83
+
When the user selects the **Log out** button, they are redirected to the Auth0 logout endpoint, which clears their session and redirects back to your app.
81
84
:::
82
-
:::checkpoint-failure
83
-
Sorry about that. Here's a couple of things to double check:
84
-
* Are your environment variables populated correctly?
85
-
* did you put the `app/api/auth/[auth0]/route.js` and `app/layout.jsx` files in the correct folder?
86
-
* make sure the domain and client ID are configured correctly
87
85
88
-
Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
89
-
:::
90
-
::::
86
+
## Run Your Application
91
87
92
-
## Add Login to Your Application {{{ data-action=code data-code="app/login.jsx" }}}
88
+
Run this command to start your Next.js development server:
93
89
94
-
Users can now log in to your application by visiting the `/api/auth/login` route handler 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.
90
+
```sh
91
+
npm run dev
92
+
```
95
93
96
-
:::note
97
-
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](https://nextjs.org/docs/api-reference/next/link). As the link points to an API route and not to a page, you should keep it as an anchor tag.
98
-
:::
94
+
Visit the url `http://localhost:3000` in your browser.
95
+
96
+
You will see:
97
+
- A **Sign up** and **Log in** button if the user is not authenticated.
98
+
- A welcome message and a **Log out** button if the user is authenticated.
99
99
100
100
::::checkpoint
101
101
:::checkpoint-default
102
-
Add the login link to your application.
103
-
-When you click it, verify that your Next.js application redirects you to the [Auth0 Universal Login](https://auth0.com/universal-login) page and that you can now log in or sign up using a username and password or a social provider.
102
+
Run Your application.
103
+
-Verify that your Next.js application redirects you to the [Auth0 Universal Login](https://auth0.com/universal-login) page and that you can now log in or sign up using a username and password or a social provider.
104
104
- Once that's complete, verify that Auth0 redirects back to your application.
105
105
:::
106
106
:::checkpoint-failure
@@ -113,60 +113,3 @@ Still having issues? Check out our [documentation](https://auth0.com/docs) or vi
## Add Logout to Your Application {{{ data-action=code data-code="app/logout.jsx" }}}
120
-
121
-
Now that you can log in to your Next.js application, you need [a way to log out](https://auth0.com/docs/logout/log-users-out-of-auth0). Add a link that points to the `/api/auth/logout` API route. Clicking it redirects your users to your [Auth0 logout endpoint](https://auth0.com/docs/api/authentication?javascript#logout) (`https://YOUR_DOMAIN/v2/logout`) and then immediately redirects them back to your application.
122
-
123
-
::::checkpoint
124
-
:::checkpoint-default
125
-
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".
126
-
:::
127
-
:::checkpoint-failure
128
-
Sorry about that. Here's a couple of things to double check:
129
-
* are your environment variables populated correctly?
130
-
* make sure that "Allowed Logout URLs" is configured correctly in your tenant
131
-
132
-
Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
133
-
:::
134
-
::::
135
-
136
-
## Show User Profile Information from a Client Component{{{ data-action=code data-code="app/profile-client/page.jsx" }}}
137
-
138
-
The Auth0 Next.js SDK helps you retrieve the [profile information](https://auth0.com/docs/users/user-profiles) associated with the logged-in user, such as their name or profile picture, to personalize the user interface.
139
-
140
-
The profile information is available through the `user` property exposed by the `useUser()` hook. Take this [Client Component](https://nextjs.org/docs/getting-started/react-essentials#client-components)`ProfileClient` as an example of how to use it.
141
-
142
-
::::checkpoint
143
-
:::checkpoint-default
144
-
Verify that you can display the `user.name` or [any other](https://auth0.com/docs/users/user-profile-structure#user-profile-attributes)`user` property within a component correctly after you have logged in.
145
-
:::
146
-
:::checkpoint-failure
147
-
Sorry about that. Here's a couple of things to double check:
148
-
* are your environment variables populated correctly?
149
-
* make sure the SDK has finished loading using the `loading` property
150
-
* make sure there are no errors in the `error` property or the console
151
-
152
-
Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
153
-
:::
154
-
::::
155
-
156
-
## Show User Profile Information from a Server Component{{{ data-action=code data-code="app/profile-server/page.jsx" }}}
157
-
158
-
The profile information is available through the `user` property exposed by the `getSession` function. Take this [Server Component](https://nextjs.org/docs/getting-started/react-essentials#server-components)`ProfileServer` as an example of how to use it.
159
-
160
-
::::checkpoint
161
-
:::checkpoint-default
162
-
Verify that you can display the `user.name` or [any other](https://auth0.com/docs/users/user-profile-structure#user-profile-attributes)`user` property within a component correctly after you have logged in.
163
-
:::
164
-
:::checkpoint-failure
165
-
Sorry about that. Here's a couple of things to double check:
166
-
* are your environment variables populated correctly?
167
-
* make sure you have successfully logged in through the `/api/auth/login` handler.
168
-
* make sure there are no errors in the console
169
-
170
-
Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
0 commit comments