Using NextAuth v5 with Next.js API Routes in the App Router

September 2, 2024 (3mo ago)

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:

npm install next-auth

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:

import NextAuth from "next-auth";
import Providers from "next-auth/providers";
 
const authOptions = {
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  // Other NextAuth configurations
};
 
export default authOptions;

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:

import NextAuth from "next-auth";
import authConfig from "./auth.config";
 
export const { auth, handlers, signOut, signIn } = NextAuth(authConfig);

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:

import { auth } from "@/auth"; // update this according to your file location.
 
export async function GET(req, res) {
  const session = await auth();
 
  if (session && session?.user) {
    // User is authenticated
    return res.status(200).json({ message: "User is authenticated", session });
  } else {
    // User is not authenticated
    return res.status(401).json({ message: "Unauthorized" });
  }
}

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.