#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
- Set up a GitHub OAuth App (in GitHub Developer Settings).
- Add
AUTH_SECRETandGITHUB_ID/SECRETto.env. - Implement the Button logic above.
- Log in and see your GitHub profile picture appear on the page!
See you tomorrow for Database Connection! ๐ฝ