Protect an API Route
Every protected API route must check session and authorization before returning data or performing mutations. Return 401 for unauthenticated requests and 403 for authenticated users without permission.
File: `pages/api/private-data.js`
import { getServerSession } from "next-auth/next";
import { authOptions } from "./auth/[...nextauth]";
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions);
if (!session) return res.status(401).json({ error: "Unauthorized" });
if (req.method !== "GET") {
res.setHeader("Allow", "GET");
return res.status(405).json({ error: "Method not allowed" });
}
return res.status(200).json({ message: "Protected data", userId: session.user.id });
}💡 Adjust the relative import path for the actual route location, and validate inputs and permissions for every operation.