Skip to content

Commit

Permalink
Update interactive Next.js Quickstart to use the Next.js v4 SDK (#10487)
Browse files Browse the repository at this point in the history
* Update interactive.md

Update interactive quickstart using nextjs v4 beta

* Update env.md

Edited env file to reflect changes based on V4 quickstart

* Create auth0

Created auth0.ts file for quickstart v4

* Rename auth0 to auth0.md

renaming

* Create middleware.md

* Create page.md

* Update page.md, remove custom classNames (#10488)

Update page.md, remove custom classNames

* Update interactive.md

Capitalized Beta in line 26 to match earlier styling

---------

Co-authored-by: Tushar Pandey <[email protected]>
Co-authored-by: rle28 <[email protected]>
Co-authored-by: Nick Gagliardi <[email protected]>
  • Loading branch information
4 people authored Jan 16, 2025
1 parent 5970c20 commit 4077d3d
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 101 deletions.
12 changes: 12 additions & 0 deletions articles/quickstart/webapp/nextjs/files/auth0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
name: "src/lib/auth0.ts"
language: javascript
---

<!-- markdownlint-disable MD041 -->

```javascript
import { Auth0Client } from "@auth0/nextjs-auth0/server";

export const auth0 = new Auth0Client();
```
4 changes: 2 additions & 2 deletions articles/quickstart/webapp/nextjs/files/env.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ language: sh

```sh
AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://${account.namespace}'
APP_BASE_URL='http://localhost:3000'
AUTH0_DOMAIN='https://${account.namespace}'
AUTH0_CLIENT_ID='${account.clientId}'
AUTH0_CLIENT_SECRET='${account.clientSecret}'
```
27 changes: 27 additions & 0 deletions articles/quickstart/webapp/nextjs/files/middleware.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
name: "src/middleware.ts"
language: javascript
---

<!-- markdownlint-disable MD041 -->

```javascript
import type { NextRequest } from "next/server";
import { auth0 } from "./lib/auth0";

export async function middleware(request: NextRequest) {
return await auth0.middleware(request);
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};
```
42 changes: 42 additions & 0 deletions articles/quickstart/webapp/nextjs/files/page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
name: "src/app/page.tsx"
language: javascript
---

<!-- markdownlint-disable MD041 -->

```javascript
import { auth0 } from "@/lib/auth0";
import './globals.css';

export default async function Home() {
// Fetch the user session
const session = await auth0.getSession();

// If no session, show sign-up and login buttons
if (!session) {
return (
<main>
<a href="/auth/login?screen_hint=signup">
<button>Sign up</button>
</a>
<a href="/auth/login">
<button>Log in</button>
</a>
</main>
);
}

// If session exists, show a welcome message and logout button
return (
<main>
<h1>Welcome, {session.user.name}!</h1>
<p>
<a href="/auth/logout">
<button>Log out</button>
</a>
</p>
</main>
);
}
```
141 changes: 42 additions & 99 deletions articles/quickstart/webapp/nextjs/interactive.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Add Login to your Next.js application
description: This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js SDK.
description: This guide demonstrates how to integrate Auth0 with any new or existing Next.js application using the Auth0 Next.js v4 SDK (Beta).
topics:
- quickstarts
- webapp
Expand All @@ -12,32 +12,30 @@ contentType: tutorial
useCase: quickstart
interactive: true
files:
- files/auth
- files/auth0
- files/env
- files/layout
- files/login
- files/logout
- files/profile-client
- files/profile-server
- files/middleware
- files/page

---

<!-- markdownlint-disable MD025 MD034 -->

# Add Login to Your Next.js Application

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

<%= include('../../_includes/_configure_auth0_interactive', {
callback: 'http://localhost:3000/api/auth/callback',
callback: 'http://localhost:3000/auth/callback',
returnTo: 'http://localhost:3000'
}) %>

## Install the Auth0 Next.js SDK
## Install the Auth0 Next.js v4 SDK

Run the following command within your project directory to install the Auth0 Next.js SDK:

```sh
npm install @auth0/nextjs-auth0
npm install @auth0/nextjs-auth0@beta
```

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.
Expand All @@ -47,60 +45,62 @@ The SDK exposes methods and variables that help you integrate Auth0 with your Ne
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):

- `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.
- `AUTH0_BASE_URL`: The base URL of your application.
- `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.
- `APP_BASE_URL`: The base URL of your application.
- `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.
- `AUTH0_CLIENT_ID`: Your Auth0 application's Client ID.
- `AUTH0_CLIENT_SECRET`: Your Auth0 application's Client Secret.

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

## Add the dynamic Route Handler {{{ data-action=code data-code="app/api/auth/[auth0]/route.js" }}}
## Create the Auth0 SDK Client {{{ data-action=code data-code="src/lib/auth0.ts" }}}

Create a file at `src/lib.auth0.ts`. This file provides methods for handling authentication, sessions and user data.

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.

## Add the Authentication Middleware {{{ data-action=code data-code="src/middleware.ts" }}}

::: note
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).
The Next.js Middleware allows you to run code before a request is completed.
:::

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

Then, import the `handleAuth` method from the SDK and call it from the `GET` export. This creates the following routes:
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 statis files and metadata.

- `/api/auth/login`: The route used to perform login with Auth0.
- `/api/auth/logout`: The route used to log the user out.
- `/api/auth/callback`: The route Auth0 will redirect the user to after a successful login.
- `/api/auth/me`: The route to fetch the user profile from.
## Add the Landing Page Content {{{ data-action=code data-code="src/app/page.tsx" }}}

## Add the `UserProvider` component {{{ data-action=code data-code="app/layout.jsx" }}}
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.

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

The authentication state exposed by `UserProvider` can be accessed in any Client Component using the `useUser()` hook.
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.

::::checkpoint
:::checkpoint-default
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.
::: note
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.
:::
:::checkpoint-failure
Sorry about that. Here's a couple of things to double check:
* Are your environment variables populated correctly?
* did you put the `app/api/auth/[auth0]/route.js` and `app/layout.jsx` files in the correct folder?
* make sure the domain and client ID are configured correctly

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
:::
::::
## Run Your Application

## Add Login to Your Application {{{ data-action=code data-code="app/login.jsx" }}}
Run this command to start your Next.js development server:

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.
```sh
npm run dev
```

:::note
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.
:::
Visit the url `http://localhost:3000` in your browser.

You will see:
- A **Sign up** and **Log in** button if the user is not authenticated.
- A welcome message and a **Log out** button if the user is authenticated.

::::checkpoint
:::checkpoint-default
Add the login link to your application.
- 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.
Run Your application.
- 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.
- Once that's complete, verify that Auth0 redirects back to your application.
:::
:::checkpoint-failure
Expand All @@ -113,60 +113,3 @@ Still having issues? Check out our [documentation](https://auth0.com/docs) or vi
::::

![Auth0 Universal Login](/media/quickstarts/universal-login.png)

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

## Add Logout to Your Application {{{ data-action=code data-code="app/logout.jsx" }}}

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.

::::checkpoint
:::checkpoint-default
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".
:::
:::checkpoint-failure
Sorry about that. Here's a couple of things to double check:
* are your environment variables populated correctly?
* make sure that "Allowed Logout URLs" is configured correctly in your tenant

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
:::
::::

## Show User Profile Information from a Client Component{{{ data-action=code data-code="app/profile-client/page.jsx" }}}

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.

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.

::::checkpoint
:::checkpoint-default
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.
:::
:::checkpoint-failure
Sorry about that. Here's a couple of things to double check:
* are your environment variables populated correctly?
* make sure the SDK has finished loading using the `loading` property
* make sure there are no errors in the `error` property or the console

Still having issues? Check out our [documentation](https://auth0.com/docs) or visit our [community page](https://community.auth0.com) to get more help.
:::
::::

## Show User Profile Information from a Server Component{{{ data-action=code data-code="app/profile-server/page.jsx" }}}

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.

::::checkpoint
:::checkpoint-default
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.
:::
:::checkpoint-failure
Sorry about that. Here's a couple of things to double check:
* are your environment variables populated correctly?
* make sure you have successfully logged in through the `/api/auth/login` handler.
* make sure there are no errors in the console

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 comments on commit 4077d3d

Please sign in to comment.