0Pricing
React Academy · Lesson

Setting Up Auth.js in Next.js App Router

Install Auth.js, configure route handlers, and add a GitHub OAuth provider.

Setting Up Auth.js in Next.js App Router is a free React Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Auth.js?

Auth.js (formerly NextAuth.js v5) is a full-featured authentication library for Next.js. It handles OAuth providers, credentials, sessions, and JWT out of the box.

Installation

Install the Auth.js beta and initialize the config file.

npm install next-auth@beta

# Create auth.ts at project root
touch auth.ts

Creating the Auth Config

Define your auth config in auth.ts at the project root with providers and callbacks.

import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [GitHub],
  callbacks: {
    session({ session, token }) {
      session.user.id = token.sub!;
      return session;
    },
  },
});

Route Handler Setup

Create a catch-all route handler in app/api/auth/[...nextauth]/route.ts that delegates to the Auth.js handlers.

// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';

export const { GET, POST } = handlers;

Environment Variables

Set the required env vars for OAuth providers. AUTH_SECRET is required for JWT signing.

# .env.local
AUTH_SECRET=your-random-secret-here

# GitHub OAuth
AUTH_GITHUB_ID=your-github-client-id
AUTH_GITHUB_SECRET=your-github-client-secret

# Generate AUTH_SECRET:
# npx auth secret

Adding Sign In/Out Buttons

Import signIn and signOut from auth.ts and use them in Server Component forms.

import { signIn, signOut } from '@/auth';

export function SignInButton() {
  return (
    <form action={async () => { 'use server'; await signIn('github'); }}>
      <button type="submit">Sign in with GitHub</button>
    </form>
  );
}

export function SignOutButton() {
  return (
    <form action={async () => { 'use server'; await signOut(); }}>
      <button type="submit">Sign out</button>
    </form>
  );
}

Reading the Session in Server Components

Call auth() from auth.ts in any Server Component or route handler to get the current session.

import { auth } from '@/auth';

export default async function ProfilePage() {
  const session = await auth();
  if (!session) redirect('/login');
  return <h1>Welcome, {session.user?.name}</h1>;
}

Protecting Pages with Middleware

Use Auth.js middleware to protect routes at the edge without running server logic on every request.

// middleware.ts
export { auth as middleware } from '@/auth';

export const config = {
  matcher: ['/dashboard/:path*', '/profile/:path*'],
};

Database Sessions

Add a database adapter (e.g., @auth/prisma-adapter) to persist sessions, users, and accounts in a database instead of JWTs.

import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from '@/lib/prisma';

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [GitHub],
  session: { strategy: 'database' },
});

Customizing the Session Type

Extend the Auth.js session types to include custom fields like user ID or role.

// types/next-auth.d.ts
import { DefaultSession } from 'next-auth';

declare module 'next-auth' {
  interface Session {
    user: { id: string; role: string } & DefaultSession['user'];
  }
}

Error Handling

Auth.js redirects to /error on auth failures by default. Create app/error/page.tsx to customize the error page.

Quick Check

Which file must you create to expose Auth.js GET and POST handlers in Next.js App Router?

Recap

Install next-auth@beta, create auth.ts with providers and callbacks, expose handlers at app/api/auth/[...nextauth]/route.ts, set AUTH_SECRET and provider env vars, and read the session with auth() in Server Components.

Frequently asked questions

Is the “Setting Up Auth.js in Next.js App Router” lesson free?

Yes — the full text of “Setting Up Auth.js in Next.js App Router” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Setting Up Auth.js in Next.js App Router”?

Install Auth.js, configure route handlers, and add a GitHub OAuth provider. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Setting Up Auth.js in Next.js App Router” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up Auth.js in Next.js App Router
  2. Session Management & useSession Hook
  3. Credentials Provider & Custom Login
  4. Middleware-Based Route Protection
← Back to React Academy