0
0
NextJSframework~5 mins

NextAuth.js (Auth.js) setup in NextJS

Choose your learning style9 modes available
Introduction

NextAuth.js helps you add user login and authentication easily to your Next.js app. It manages sign-in, sign-out, and user sessions securely.

You want users to log in with email or social accounts like Google or GitHub.
You need to protect pages so only signed-in users can see them.
You want to manage user sessions without building your own backend.
You want a quick way to add authentication without complex setup.
Syntax
NextJS
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    }),
    // add more providers here
  ],
  // other options like callbacks, pages, session
};

export default NextAuth(authOptions);

Put this code in pages/api/auth/[...nextauth].js to create the auth API route.

Use environment variables to keep your client IDs and secrets safe.

Examples
Basic setup with Google as the only sign-in provider.
NextJS
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ]
});
Setup with GitHub provider and JWT session strategy.
NextJS
import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    })
  ],
  session: {
    strategy: "jwt"
  }
});
Sample Program

This is a complete NextAuth.js setup file for Next.js API route. It uses Google login and custom sign-in page.

NextJS
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET
    })
  ],
  pages: {
    signIn: "/auth/signin"
  }
});
OutputSuccess
Important Notes

Remember to add your environment variables in a .env.local file.

Use useSession() hook in your components to get user info and login status.

Protect pages by checking session on server or client side.

Summary

NextAuth.js makes adding login easy in Next.js apps.

Set up providers with client IDs and secrets.

Use the API route /api/auth/[...nextauth] to handle auth.