Module 7: Authentication

Secure Auth with Auth.js (NextAuth v5)

Setup (v5 Beta)

Auth.js v5 is designed for the App Router.

npm install next-auth@beta

Create auth.js config file:

// auth.js
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [GitHub],
})

Create the Route Handler:

// app/api/auth/[...nextauth]/route.js
import { handlers } from "@/auth"
export const { GET, POST } = handlers

Protecting Routes

1. Middleware (Recommended)

Protect routes at the edge before they render.

// middleware.js
import { auth } from "@/auth"

export default auth((req) => {
  if (!req.auth && req.nextUrl.pathname !== "/login") {
    const newUrl = new URL("/login", req.nextUrl.origin)
    return Response.redirect(newUrl)
  }
})

export const config = {
  matcher: ["/dashboard/:path*"],
}

2. In Server Components

import { auth } from "@/auth"
import { redirect } from "next/navigation"

export default async function Dashboard() {
  const session = await auth()
  if (!session) redirect("/login")
  
  return 
Welcome, {session.user.name}
}

Client Side Usage

Wrap your app in SessionProvider to use useSession.

// app/layout.js
import { SessionProvider } from "next-auth/react"

export default function Layout({ children }) {
  return (
    
      {children}
    
  )
}