Next.js › API Routes
How can you protect an API route so that only authenticated users can access it?
IntermediateAnswer
You check for a valid session or authentication token at the start of your handler, usually by reading a cookie or an authorization header, and return a 401 unauthorized response immediately if the check fails, before running any of the protected logic.
export default function handler(req, res) {
const token = req.cookies.session;
if (!token) {
return res.status(401).json({ error: 'Not authenticated' });
}
res.status(200).json({ secret: 'protected data' });
}Real-world example An account settings API route checks for a valid session cookie before allowing a user to update their profile information, blocking anyone who is not properly signed in.