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
Copy file name to clipboardExpand all lines: articles/quickstart/webapp/nextjs/01-login.md
+87-51Lines changed: 87 additions & 51 deletions
Original file line number
Diff line number
Diff line change
@@ -23,7 +23,7 @@ useCase: quickstart
23
23
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
26
+
npm i @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://reactjs.org/docs/context.html"target="_blank"rel="noreferrer">React Context</a> with <ahref="https://reactjs.org/docs/hooks-overview.html"target="_blank"rel="noreferrer">React Hooks</a> on the frontend.
The SDK will read these values from the Node.js process environment and automatically configure itself.
50
50
51
-
### Add the dynamic API route handler
51
+
### Create the Auth0 SDK Client
52
52
53
-
Create a file at `app/api/auth/<a href="https://nextjs.org/docs/app/building-your-application/routing/route-handlers#dynamic-route-segments" target="_blank" rel="noreferrer">auth0/route.js`. This is your Route Handler file with a Dynamic Route Segment</a>.
53
+
Create a file at `src/lib/auth0.ts`. This file provides methods for handling authentication, sessions and user data.
54
54
55
-
Then, import the `handleAuth` method from the SDK and call it from the `GET` export.
55
+
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.
-`/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.
64
+
### Add the Authentication Middleware
70
65
71
66
::: 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>.
67
+
The Next.js Middleware allows you to run code before a request is completed.
73
68
:::
74
69
75
-
### Add the `UserProvider` component
76
-
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 <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`.
70
+
Create a file at `src/middleware.ts`. This file is used to enforce authentication on specific routes.
78
71
79
-
Create the file `app/layout.jsx` as follows:
72
+
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.
The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook.
96
+
### Add the Landing Page Content
97
97
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.
100
-
:::
98
+
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.
101
99
102
-
## Add Login to Your Application
100
+
Edit the file `src/app/page.tsx`to add the `auth0.getSession()` method to determine if the user is logged in by retrieving the user session.
103
101
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.
102
+
If there is no user session, the method returns `null` and the app displays the **Sign up** or **Log in** buttons. If a user sessions exists, the app displays a welcome message with the user's name and a **Log out** button.
105
103
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.
104
+
```javascript
105
+
// src/app/page.tsx
106
+
import { auth0 } from"@/lib/auth0";
107
+
import'./globals.css';
108
+
109
+
exportdefaultasyncfunctionHome() {
110
+
// Fetch the user session
111
+
constsession=awaitauth0.getSession();
112
+
113
+
// If no session, show sign-up and login buttons
114
+
if (!session) {
115
+
return (
116
+
<main>
117
+
<a href="/auth/login?screen_hint=signup">
118
+
<button>Sign up</button>
119
+
</a>
120
+
<a href="/auth/login">
121
+
<button>Log in</button>
122
+
</a>
123
+
</main>
124
+
);
125
+
}
126
+
127
+
// If session exists, show a welcome message and logout button
128
+
return (
129
+
<main>
130
+
<h1>Welcome, {session.user.name}!</h1>
131
+
<p>
132
+
<a href="/auth/logout">
133
+
<button>Log out</button>
134
+
</a>
135
+
</p>
136
+
</main>
137
+
);
138
+
}
139
+
```
140
+
::: note
141
+
The Logout functionality is already included in the file src/app/page.tsx. 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.
108
142
:::
109
143
110
-
```html
111
-
<ahref="/api/auth/login">Login</a>
144
+
### Run the Sample
145
+
146
+
Run this command to start your Next.js development server:
147
+
148
+
```sh
149
+
npm run dev
112
150
```
151
+
Visit the url `http://localhost:3000` in your browser.
152
+
153
+
You will see:
154
+
155
+
A **Sign up** and **Log in** button if the user is not authenticated.
156
+
A welcome message and a **Log out** button if the user is authenticated.
113
157
114
158
:::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.
159
+
160
+
Run your application.
161
+
162
+
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
163
117
164
Once that's complete, verify that Auth0 redirects back to your application.
118
165
:::
@@ -121,17 +168,6 @@ Once that's complete, verify that Auth0 redirects back to your application.
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.
127
-
128
-
```html
129
-
<ahref="/api/auth/logout">Logout</a>
130
-
```
131
-
132
-
:::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".
0 commit comments