Installing Auth.js
Start by installing the appropriate package for your framework:
npm install next-auth@beta
@auth/core
is not necessary.Setup Environment
The only environment variable that is mandatory is the AUTH_SECRET
. This is a random value used by the library to encrypt tokens and email
verification hashes. (See Deployment to learn more). You can generate one via running:
npx auth secret
Alternatively, you can use the openssl
CLI, openssl rand -base64 33
.
Then add it to your .env.local
file:
AUTH_SECRET=secret
Configure
Next, create the Auth.js config object. This is where you can control the behaviour of the library and specify custom authentication logic, adapters, etc. We recommend all frameworks to create an auth.ts
file in the project. In this file we’ll pass in all the options to the framework specific initalization function and then export the route handler(s), signin and signout methods, and more.
You can name this file whatever you want and place it wherever you like.
Start by creating a new auth.ts
file at the root of your app with the following content:
import NextAuth from "next-auth"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [],
})
Add a Route Handler under /app/api/auth/[...nextauth]/route.ts
.
import { handlers } from "@/auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
Add Middleware to keep the session alive.
export { auth as middleware } from "auth"
Setup Authentication Methods
With that, the basic setup is complete! Next we’ll setup the first authentication methods and fill out that providers
array.