Authentication is an essential aspect of modern web applications, and Next.js makes it easy with NextAuth.js. This flexible library provides a robust and secure way to integrate authentication using OAuth providers like Google, GitHub, and more. In this guide, we'll walk through the steps of setting up NextAuth.js and discuss key features, customizations, and best practices to secure your Next.js applications.
To get started with NextAuth.js, you need to install the library in your Next.js project. Run the following command to install NextAuth:
npm install next-auth
Once installed, you need to configure an API route in your project. This will handle all authentication-related actions. Create a new file at /pages/api/auth/[...nextauth].js
:
import NextAuth from 'next-auth';
import Providers from 'next-auth/providers';
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
});
To securely store your API keys, create a .env.local
file in your root directory, and add your credentials like this:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NEXTAUTH_URL=http://localhost:3000
useSession
Hook
Now that NextAuth.js is set up, you can use the useSession
hook to check if a user is authenticated or not:
import { useSession, signIn, signOut } from 'next-auth/react';
export default function HomePage() {
const { data: session } = useSession();
if (session) {
return (
Welcome, {session.user.name}!
);
}
return (
You are not logged in.
);
}
You can customize the session and JWT tokens by adding callback functions in the NextAuth.js configuration. Here's an example of adding a user role to the token:
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
callbacks: {
async jwt(token, user) {
if (user) {
token.role = user.role; // Add custom fields
}
return token;
},
async session(session, token) {
session.user.role = token.role;
return session;
},
},
});
If you prefer to have a custom sign-in page, NextAuth.js provides a way to override the default UI:
export default NextAuth({
providers: [
Providers.Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
pages: {
signIn: '/auth/signin', // Custom sign-in page
},
});
// pages/auth/signin.js
export default function SignIn() {
return (
Sign In
);
}
To secure API routes, use the getSession
function to check if a session exists before proceeding:
import { getSession } from 'next-auth/react';
export default async (req, res) => {
const session = await getSession({ req });
if (!session) {
return res.status(401).json({ error: 'You must be signed in.' });
}
// Protected content
res.status(200).json({ message: 'Authenticated content' });
};
NextAuth.js is a highly flexible authentication solution for Next.js applications. Whether you need OAuth support, passwordless sign-ins, or database sessions, NextAuth.js makes it straightforward to implement secure authentication in your app. By following the steps in this guide, you can set up a robust authentication system and customize it to fit your needs.