DEV Community

Jeet Bhalani
Jeet Bhalani

Posted on

Getting Started with NextAuth.js: Authentication for Next.js

Authentication is a must-have for most web apps, and NextAuth.js makes it incredibly easy to set up authentication in a Next.js project. Whether you're using OAuth providers like GitHub and Google, or custom credentials, NextAuth.js has you covered.

In this guide, I'll walk you through setting up NextAuth.js from scratch and share some tips to make your authentication flow seamless.

What is NextAuth.js?

NextAuth.js is a flexible authentication library built for Next.js. It supports multiple authentication strategies, including:

  • OAuth (Google, GitHub, Twitter, etc.)
  • Credentials-based authentication (email/password, magic links, etc.)
  • JWT (JSON Web Tokens) for secure, stateless authentication

With minimal setup, you can add authentication to your Next.js app without handling user sessions manually.

Setting Up NextAuth.js

1️⃣ Install NextAuth.js
Run the following command to install NextAuth.js in your Next.js project:

npm install next-auth
# or
yarn add next-auth

Enter fullscreen mode Exit fullscreen mode

2️⃣ Create an API Route
NextAuth.js requires an API route to handle authentication. Create a new file at pages/api/auth/[...nextauth].ts (or .js if you're not using TypeScript) and add the following code:

import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async session({ session, token }) {
      session.user.id = token.sub;
      return session;
    },
  },
});

Enter fullscreen mode Exit fullscreen mode
  • We're using GitHub as the authentication provider.
  • The API route handles login and logout flows.
  • We're modifying the session object to include the user ID.

3️⃣ Set Up Environment Variables.
To keep your API keys secure, create a .env.local file in the root directory and add:


GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
NEXTAUTH_URL=http://localhost:3000

Enter fullscreen mode Exit fullscreen mode
  • NextAuth.js uses environment variables to securely store API keys.
  • NEXTAUTH_URL ensures OAuth redirects work correctly.

4️⃣ Implement Authentication in a Component.
Now, let’s add login and logout functionality to a React component using the useSession hook from next-auth/react:

import { useSession, signIn, signOut } from "next-auth/react";

export default function AuthButton() {
  const { data: session } = useSession();

  if (session) {
    return (
      <div>
        <p>Welcome, {session.user.name}</p>
        <button onClick={() => signOut()}>Sign Out</button>
      </div>
    );
  }
  return <button onClick={() => signIn("github")}>Sign In with GitHub</button>;
}

Enter fullscreen mode Exit fullscreen mode
  • If the user is logged in, we show their name and a sign-out button.
  • If not, we display a Sign In with GitHub button.

5️⃣ Protecting Pages with Authentication.
If you want to restrict access to certain pages (e.g., a dashboard), you can use getServerSideProps to check the session:

import { getSession } from "next-auth/react";

export async function getServerSideProps(context) {
  const session = await getSession(context);

  if (!session) {
    return {
      redirect: {
        destination: "/api/auth/signin",
        permanent: false,
      },
    };
  }
  return { props: { session } };
}

Enter fullscreen mode Exit fullscreen mode
  • It ensures that only authenticated users can access the page.
  • Unauthenticated users are redirected to the sign-in page.

🎯 Wrapping Up

With just a few steps, we've integrated NextAuth.js into a Next.js project. This setup works for both OAuth providers (GitHub, Google, etc.) and custom authentication strategies.

🔥 Next Steps

  • Add more authentication providers like Google or Twitter.
  • Customize user sessions with database integration.
  • Explore NextAuth.js callbacks and events for advanced use cases.

Top comments (0)