From 21e41d3ae94769a2382372acb54ff485177be1ce Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:02:05 +0100 Subject: [PATCH 1/8] Update interactive.md Update interactive quickstart using nextjs v4 beta --- .../quickstart/webapp/nextjs/interactive.md | 141 ++++++------------ 1 file changed, 42 insertions(+), 99 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/interactive.md b/articles/quickstart/webapp/nextjs/interactive.md index 360ae01269..83db14d548 100644 --- a/articles/quickstart/webapp/nextjs/interactive.md +++ b/articles/quickstart/webapp/nextjs/interactive.md @@ -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 @@ -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 + --- # 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. @@ -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 `` 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 @@ -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. -::: -:::: From e691b184897d61d5b12197e7764684113f820372 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:05:29 +0100 Subject: [PATCH 2/8] Update env.md Edited env file to reflect changes based on V4 quickstart --- articles/quickstart/webapp/nextjs/files/env.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/files/env.md b/articles/quickstart/webapp/nextjs/files/env.md index 22abaa809d..c582873ef0 100644 --- a/articles/quickstart/webapp/nextjs/files/env.md +++ b/articles/quickstart/webapp/nextjs/files/env.md @@ -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}' ``` From 5e2f2351a51175d1c310bbfb950a32022a2e7c37 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:09:29 +0100 Subject: [PATCH 3/8] Create auth0 Created auth0.ts file for quickstart v4 --- articles/quickstart/webapp/nextjs/files/auth0 | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 articles/quickstart/webapp/nextjs/files/auth0 diff --git a/articles/quickstart/webapp/nextjs/files/auth0 b/articles/quickstart/webapp/nextjs/files/auth0 new file mode 100644 index 0000000000..ef0bc05299 --- /dev/null +++ b/articles/quickstart/webapp/nextjs/files/auth0 @@ -0,0 +1,12 @@ +--- +name: "src/lib/auth0.ts" +language: javascript +--- + + + +```javascript +import { Auth0Client } from "@auth0/nextjs-auth0/server"; + +export const auth0 = new Auth0Client(); +``` From cbb0bb1ab3b772319bb853ddaf6f2ac284e566c9 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:11:03 +0100 Subject: [PATCH 4/8] Rename auth0 to auth0.md renaming --- articles/quickstart/webapp/nextjs/files/{auth0 => auth0.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename articles/quickstart/webapp/nextjs/files/{auth0 => auth0.md} (100%) diff --git a/articles/quickstart/webapp/nextjs/files/auth0 b/articles/quickstart/webapp/nextjs/files/auth0.md similarity index 100% rename from articles/quickstart/webapp/nextjs/files/auth0 rename to articles/quickstart/webapp/nextjs/files/auth0.md From 08ab6efec690aec494d80a24bcc280f0cb38a5a6 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:12:21 +0100 Subject: [PATCH 5/8] Create middleware.md --- .../webapp/nextjs/files/middleware.md | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 articles/quickstart/webapp/nextjs/files/middleware.md diff --git a/articles/quickstart/webapp/nextjs/files/middleware.md b/articles/quickstart/webapp/nextjs/files/middleware.md new file mode 100644 index 0000000000..143a21f55f --- /dev/null +++ b/articles/quickstart/webapp/nextjs/files/middleware.md @@ -0,0 +1,27 @@ +--- +name: "src/middleware.ts" +language: javascript +--- + + + +```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).*)", + ], +}; +``` From 631cde73391ade3278eba47682bd98f5b1569548 Mon Sep 17 00:00:00 2001 From: Carlos Fung Date: Thu, 16 Jan 2025 13:14:57 +0100 Subject: [PATCH 6/8] Create page.md --- .../quickstart/webapp/nextjs/files/page.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 articles/quickstart/webapp/nextjs/files/page.md diff --git a/articles/quickstart/webapp/nextjs/files/page.md b/articles/quickstart/webapp/nextjs/files/page.md new file mode 100644 index 0000000000..e208bac426 --- /dev/null +++ b/articles/quickstart/webapp/nextjs/files/page.md @@ -0,0 +1,42 @@ +--- +name: "src/app/page.tsx" +language: javascript +--- + + + +```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 ( +
+ + + + + + +
+ ); + } + + // If session exists, show a welcome message and logout button + return ( +
+

Welcome, {session.user.name}!

+

+ + + +

+
+ ); +} +``` From 160d0d1eef935e01ccf012c7cb44457c68ec0df6 Mon Sep 17 00:00:00 2001 From: Tushar Pandey Date: Thu, 16 Jan 2025 18:52:48 +0530 Subject: [PATCH 7/8] Update page.md, remove custom classNames (#10488) Update page.md, remove custom classNames --- articles/quickstart/webapp/nextjs/files/page.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/articles/quickstart/webapp/nextjs/files/page.md b/articles/quickstart/webapp/nextjs/files/page.md index e208bac426..5bc12c8dfa 100644 --- a/articles/quickstart/webapp/nextjs/files/page.md +++ b/articles/quickstart/webapp/nextjs/files/page.md @@ -16,9 +16,9 @@ export default async function Home() { // If no session, show sign-up and login buttons if (!session) { return ( -
+
- + From 9f4eff033be1ae25abc902c08177c76fa3a7533a Mon Sep 17 00:00:00 2001 From: rle28 <133895406+rle28@users.noreply.github.com> Date: Thu, 16 Jan 2025 11:10:06 -0500 Subject: [PATCH 8/8] Update interactive.md Capitalized Beta in line 26 to match earlier styling --- articles/quickstart/webapp/nextjs/interactive.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/articles/quickstart/webapp/nextjs/interactive.md b/articles/quickstart/webapp/nextjs/interactive.md index 83db14d548..20d02a1d1d 100644 --- a/articles/quickstart/webapp/nextjs/interactive.md +++ b/articles/quickstart/webapp/nextjs/interactive.md @@ -23,7 +23,7 @@ files: # 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 v4 SDK (beta). 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/auth/callback',