Skip to content

Commit 9dfc088

Browse files
authored
Updated non-interactive nextJS guide with SDK 4 instructions.
1 parent 76c61f4 commit 9dfc088

File tree

1 file changed

+87
-51
lines changed

1 file changed

+87
-51
lines changed

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

Lines changed: 87 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ 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
26+
npm i @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://reactjs.org/docs/context.html" target="_blank" rel="noreferrer">React Context</a> with <a href="https://reactjs.org/docs/hooks-overview.html" target="_blank" rel="noreferrer">React Hooks</a> on the frontend.
@@ -48,71 +48,118 @@ AUTH0_CLIENT_SECRET='${account.clientSecret}'
4848

4949
The SDK will read these values from the Node.js process environment and automatically configure itself.
5050

51-
### Add the dynamic API route handler
51+
### Create the Auth0 SDK Client
5252

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.
5454

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.
5656

5757
```javascript
58-
// app/api/auth/[auth0]/route.js
59-
import { handleAuth } from '@auth0/nextjs-auth0';
58+
// src/lib/auth0.ts
59+
import { Auth0Client } from "@auth0/nextjs-auth0/server";
6060

61-
export const GET = handleAuth();
61+
export const auth0 = new Auth0Client();
6262
```
6363

64-
This creates the following routes:
65-
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.
64+
### Add the Authentication Middleware
7065

7166
::: 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>.
67+
The Next.js Middleware allows you to run code before a request is completed.
7368
:::
7469

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 <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`.
70+
Create a file at `src/middleware.ts`. This file is used to enforce authentication on specific routes.
7871

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.
8073

81-
```jsx
82-
// app/layout.jsx
83-
import { UserProvider } from '@auth0/nextjs-auth0/client';
74+
```javascript
75+
// src/middleware.ts
76+
import type { NextRequest } from "next/server";
77+
import { auth0 } from "./lib/auth0";
8478

85-
export default function RootLayout({ children }) {
86-
return (
87-
<html lang="en">
88-
<UserProvider>
89-
<body>{children}</body>
90-
</UserProvider>
91-
</html>
92-
);
79+
export async function middleware(request: NextRequest) {
80+
return await auth0.middleware(request);
9381
}
82+
83+
export const config = {
84+
matcher: [
85+
/*
86+
* Match all request paths except for the ones starting with:
87+
* - _next/static (static files)
88+
* - _next/image (image optimization files)
89+
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
90+
*/
91+
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
92+
],
93+
};
9494
```
9595

96-
The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook.
96+
### Add the Landing Page Content
9797

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.
10199

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.
103101

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.
105103

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.
104+
```javascript
105+
// src/app/page.tsx
106+
import { auth0 } from "@/lib/auth0";
107+
import './globals.css';
108+
109+
export default async function Home() {
110+
// Fetch the user session
111+
const session = await auth0.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.
108142
:::
109143

110-
```html
111-
<a href="/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
112150
```
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.
113157

114158
:::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.
159+
160+
Run your application.
161+
162+
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.
116163

117164
Once that's complete, verify that Auth0 redirects back to your application.
118165
:::
@@ -121,17 +168,6 @@ Once that's complete, verify that Auth0 redirects back to your application.
121168

122169
<%= include('../_includes/_auth_note_dev_keys') %>
123170

124-
## Add Logout to Your Application
125-
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.
127-
128-
```html
129-
<a href="/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".
134-
:::
135171

136172
## Show User Profile Information
137173

0 commit comments

Comments
 (0)