#nextjs #auth #next-auth #security

Day 22 โ€” Authentication: Auth.js (NextAuth) v5

๐Ÿงญ Day 22 โ€” Authentication: Auth.js (NextAuth) v5

Zero to Hero โ€” Hands-on Next.js Tutorial

Welcome to Week 4! Advanced Patterns. Authentication is hard. Implementing OAuth (Google/GitHub Login), Sessions, and JWTs manually is a nightmare. We use Auth.js (formerly NextAuth).


๐ŸŸฆ 1. Setup

The new v5 is designed for the App Router.

npm install next-auth@beta

Create auth.config.ts:

import type { NextAuthConfig } from 'next-auth';
 
export const authConfig = {
  pages: {
    signIn: '/login', // Redirect here if unauthenticated
  },
  callbacks: {
    authorized({ auth, request: { nextUrl } }) {
      const isLoggedIn = !!auth?.user;
      const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
      if (isOnDashboard) {
        if (isLoggedIn) return true;
        return false; // Redirect unauthenticated users
      }
      return true;
    },
  },
  providers: [], // Add providers later
} satisfies NextAuthConfig;

๐ŸŸฉ 2. Initialize (auth.ts)

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
import GitHub from 'next-auth/providers/github';
 
export const { auth, signIn, signOut } = NextAuth({
  ...authConfig,
  providers: [GitHub], // Add GitHub Provider
});

๐ŸŸง 3. The Login Server Action

You can trigger login via a Server Action!

import { signIn } from '@/auth';

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

๐ŸŸฅ 4. Accessing Session

In Server Components:

import { auth } from '@/auth';

export default async function Page() {
  const session = await auth();
  if (!session?.user) return <p>Not logged in</p>;
  
  return <p>Hello, {session.user.name}</p>;
}

๐Ÿงช Challenge: Day 22

  1. Set up a GitHub OAuth App (in GitHub Developer Settings).
  2. Add AUTH_SECRET and GITHUB_ID/SECRET to .env.
  3. Implement the Button logic above.
  4. Log in and see your GitHub profile picture appear on the page!

See you tomorrow for Database Connection! ๐Ÿ’ฝ