🛡️Authenticated API

Protect API routes from unauthenticated access

While building the backend (routes) of your application, you will probably have a protected section.

That means that only authenticated users can access those pages and API endpoints.

For instance, you could protect the /api/user route to return the current authenticated user details, only if the user is authenticated.

The authentication check is different in case you use NextAuth or Supabase Auth.

NextAuth

To verify if a user is authenticated in an API route, using NextAuth, use the following code:

import { getServerSession } from "next-auth/next";

/* ... */

export async function GET() {
  // retrieve the current session
  const session = await getServerSession(authOptions);
  
  // check if the session exists and user email is set
  if (!session || !session?.user?.email) {
    return NextResponse.json(
      { error: "Unauthorized" },
      { status: HttpStatusCode.Unauthorized }
    );
  } 
}

Supabase Auth

To verify if a user is authenticated in an API route, using NextAuth, use the following code:

import { getSupabaseServerClient } from "@/libs/supabase";

/* ... */

export async function GET() {
  // retrieve the current session
  const supabase = getSupabaseServerClient();
  const supabaseSession = await supabase.auth.getSession();
  const session = supabaseSession?.data.session;
  
  // check if the session exists and user email is set
  if (!session || !session?.user?.email) {
    return NextResponse.json(
      { error: "Unauthorized" },
      { status: HttpStatusCode.Unauthorized }
    );
  } 
}

Last updated