Installing and Configuring Auth.js in Next.js
Let us configure Auth.js (v5) inside a Next.js App Router application.
1. Installing Package Dependencies
Install the Next.js wrapper package for Auth.js:
# Install the v5 Auth.js Next.js integration package
npm install next-auth@beta2. Generating the Secret Key
Auth.js requires an encryption secret to sign JWT session cookies. Run this shell command to generate a secure random string:
# Generate secret key
npx auth secretThis creates an AUTH_SECRET entry inside your .env configuration file:
AUTH_SECRET="your-generated-secret-string"3. Creating the Config File (auth.ts)
Create an auth.ts file in your application root folder (or inside src/) to define authentication configurations:
// auth.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
GitHub({
clientId: process.env.AUTH_GITHUB_ID,
clientSecret: process.env.AUTH_GITHUB_SECRET,
}),
],
// Custom auth page overrides (optional)
pages: {
signIn: "/login",
},
});4. Registering the API Router Handler
Auth.js handles registration redirects and callback responses using a catch-all API route handler.
Create the folder structure app/api/auth/[...nextauth]/ and create a route.ts file inside:
// app/api/auth/[...nextauth]/route.ts
import { handlers } from "../../../../auth";
// Export GET and POST handlers to process incoming auth web requests
export const { GET, POST } = handlers;Published on Last updated: