网页 综合 更新时间 2026-09-16 00:00:00

How to implement authentication in Next.js

自动蜘蛛 nextjs.org 正文约 5348 字
How to implement authentication in Next.js
Understanding authentication is crucial for protecting your application's data. This page will guide you through what React and Next.js features to use to implement auth.
Before starting, it helps to break down the process into three concepts:
This diagram shows the authentication flow using React and Next.js features:
The examples on this page walk through basic username and password auth for educational purposes. While you can implement a custom auth solution, for increased security and simplicity, we recommend using an authentication library. These offer built-in solutions for authentication, session management, and authorization, as well as additional features such as social logins, multi-factor authentication, and role-based access control. You can find a list in the Auth Libraries section.
With Cache Components enabled, reading the session and caching per-user data follow specific rules. See Authentication with Cache Components.
You can use the <form> element with React's Server Actions and useActionState to capture user credentials, validate form fields, and call your Authentication Provider's API or database.
Since Server Actions always execute on the server, they provide a secure environment for handling authentication logic.
Here are the steps to implement signup/login functionality:
To capture user credentials, create a form that invokes a Server Action on submission. For example, a signup form that accepts the user's name, email, and password:
Use the Server Action to validate the form fields on the server. If your authentication provider doesn't provide form validation, you can use a schema validation library like Zod, Valibot or Yup.
Using Zod as an example, you can define a form schema with appropriate error messages:
To prevent unnecessary calls to your authentication provider's API or database, you can return early in the Server Action if any form fields do not match the defined schema.
Back in your <SignupForm />, you can use React's useActionState hook to display validation errors while the form is submitting:
After validating form fields, you can create a new user account or check if the user exists by calling your authentication provider's API or database.
Continuing from the previous example:
After successfully creating the user account or verifying the user credentials, you can create a session to manage the user's auth state. Depending on your session management strategy, the session can be stored in a cookie or database, or both. Continue to the Session Management section to learn more.
Session management ensures that the user's authenticated state is preserved across requests. It involves creating, storing, refreshing, and deleting sessions or tokens.
There are two types of sessions:
While you can use either method, or both, we recommend using a session management library such as iron-session or Jose.
To create and manage stateless sessions, there are a few steps you need to follow:
In addition to the above, consider adding functionality to update (or refresh) the session when the user returns to the application, and delete the session when the user logs out.
Check if your auth library includes session management.
There are a few ways you can generate secret key to sign your session. For example, you may choose to use the openssl command in your terminal:
This command generates a 32-character random string that you can use as your secret key and store in your environment variables file:
You can then reference this key in your session management logic:
Next, you can use your preferred session management library to encrypt and decrypt sessions. Continuing from the previous example, we'll use Jose and React's server-only package to ensure that your session management logic is only executed on the server.
To store the session in a cookie, use the Next.js cookies API. The cookie should be set on the server, and include the recommended options:
Please refer to MDN for more information on each of these options.
Back in your Server Action, you can invoke the createSession() function, and use the redirect() API to redirect the user to the appropriate page:
You can also extend the session's expiration time. This is useful for keeping the user logged in after they access the application again. For example:
Check if your auth library supports refresh tokens, which can be used to extend the user's session.
To delete the session, you can delete the cookie:
Then you can reuse the deleteSession() function in your application, for example, on logout:
To create and manage database sessions, you'll need to follow these steps:
After implementing session management, you'll need to add authorization logic to control what users can access and do within your application. Continue to the Authorization section to learn more.
Once a user is authenticated and a session is created, you can implement authorization to control what the user can access and do within your application.
There are two main types of authorization checks:
For both cases, we recommend:
There are some cases where you may want to use Proxy and redirect users based on permissions:
However, since Proxy runs on every route, including prefetched routes, it's important to only read the session from the cookie (optimistic checks), and avoid database checks to prevent performance issues.
访问原文 返回搜索 https://nextjs.org/docs/app/guides/authentication
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。