🍪 Note: Our web-capstone-docs subdomain is a cookie-free zone.
Additional Libraries
Protect Backend

Protect Backend

In the backend the useSession hook is not available. But NextAuth provides another method to get the session if the user is logged in: getServerSession(). This method consumes three arguments: request, response and authOptions. request and response are available inside your handler function in the API Route. authOptions can be imported from your nextauth configuration file: /pages/api/auth/[...next-auth].js. Don't forget to import the method itself from "next-auth/react".

💡

Take a look at the example implementation (opens in a new tab) on GitHub. Each step in this chapter is stored in a single commit.

Protect the POST route

Import method and config file

import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
Make sure the import path of the authOptions is correct.

Inside the handler function get the session

export default async function handler(request, response) {
  const session = await getServerSession(request, response, authOptions);
  //...
}

Use the session to either send the data to the DB or not

 else if (request.method === "POST") {
  try {
    if (session) {
      const placeData = request.body;
      await Place.create(placeData);
      response.status(201).json({ status: "Place created" });
    } else {
      response.status(401).json({ status: "Not authorized" });
    }
  } catch (error)  //{...}
}

Protect the GET Route

if (request.method === "GET") {
  try {
    if (session) {
      const places = await Place.find();
      response.status(200).json(places);
    } else {
      response.status(401).json({ status: "Not authorized" });
    }
  } catch (error) //{...}
}

You can use an Early Return here as well:

export default async function handler(request, response) {
  const session = await getServerSession(request, response, authOptions);
  if (!session){
    response.status(401).json({ status: "Not authorized" });
    return;
  } 
  // do the requests...
}

You may have other API routes in your project as well, e.g. a dynamic route. Make sure to protect each route with a login as in the examples above or with an early return statement.