NextAuth.js is a popular authentication library for Next.js applications, offering robust support for a variety of authentication methods, including OAuth, email/password, and custom strategies. With the release of NextAuth v5, there have been significant changes to its integration with Next.js, especially concerning the usage of the auth
function with API routes in the app router.
Creating NextAuth config
To get started, you'll need to install the required dependencies:
Next, create a new file called auth.config.js
(or auth.config.ts
if you're using TypeScript). This file will contain your NextAuth configuration:
This setup configures NextAuth to use Google as an authentication provider. You can add other providers as needed.
Configuring NextAuth with the config
Next, create a new file called auth.js
(or auth.ts
if you're using TypeScript). This file will contain your NextAuth configuration and export the auth
function:
Using the auth
Function in API Routes
With the app router, the auth
function from NextAuth v5 is essential for managing sessions and handling requests within API routes. The function returns a session object that you can use to determine whether a user is authenticated.
Here's an example of how to use the auth
function in an API route:
In this example, the GET
function checks if a session exists. If the user is authenticated, it returns a 200 status with the session information. If not, it returns a 401 status, indicating that the request is unauthorized.
Summary
NextAuth v5 integrates seamlessly with Next.js's app router, especially with the use of API routes. The auth
function is crucial for managing authentication and sessions within your application. By exporting this function from your NextAuth configuration, you can easily access session data and enforce authentication across your API routes.
This setup provides a flexible and secure way to manage user authentication in your Next.js applications, ensuring that sensitive routes are protected and accessible only to authenticated users.