Next.js, being a React framework, doesn't have built-in authentication, but you can implement it using various authentication providers or custom solutions. Here, I'll outline a general approach using a popular authentication library called NextAuth.js along with a custom server.
Install the necessary packages:
bashnpm install next-auth
Next.js requires a custom server for certain advanced features like authentication. Create a file named server.js
in your project root:
javascript// server.js
const express = require('express');
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const nextAuth = require('next-auth');
const nextAuthConfig = require('./next-auth-config');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(
nextAuth({
...nextAuthConfig,
pages: {
signIn: '/auth/signin',
signOut: '/auth/signout',
error: '/auth/error',
verifyRequest: '/auth/verify-request',
newUser: null, // Will disable the default new account creation screen
},
})
);
server.all('*', (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
});
createServer(server).listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
});
Create a file named next-auth-config.js
in your project root:
javascript// next-auth-config.js
export default {
providers: [
// Add your authentication providers here (e.g., Google, GitHub, etc.)
// Example with Google provider:
// {
// id: 'google',
// name: 'Google',
// type: 'oauth',
// version: '2.0',
// scope: 'openid profile email',
// clientId: 'YOUR_GOOGLE_CLIENT_ID',
// clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
// },
],
callbacks: {
async session(session, user) {
return Promise.resolve({
...session,
user: {
...session.user,
id: user.id,
},
});
},
},
};
Add the necessary provider configurations for the authentication providers you want to use.
You can protect your pages by adding authentication checks. For example:
jsx// pages/dashboard.js
import { useSession } from 'next-auth/react';
function Dashboard() {
const { data: session } = useSession();
if (!session) {
return <p>You need to be authenticated to access this page.</p>;
}
return (
<div>
<h1>Dashboard</h1>
<p>Welcome, {session.user.name}!</p>
</div>
);
}
export default Dashboard;
package.json
Update your package.json
to use the custom server:
json"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
Run your application:
bashnpm run dev
This setup allows you to add authentication to your Next.js application using NextAuth.js and custom server configuration. Adjust the configuration and providers according to your needs.