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";/* ... */exportasyncfunctionGET() {// retrieve the current sessionconstsession=awaitgetServerSession(authOptions);// check if the session exists and user email is setif (!session ||!session?.user?.email) {returnNextResponse.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";/* ... */exportasyncfunctionGET() {// retrieve the current sessionconstsupabase=getSupabaseServerClient();constsupabaseSession=awaitsupabase.auth.getSession();constsession=supabaseSession?.data.session;// check if the session exists and user email is setif (!session ||!session?.user?.email) {returnNextResponse.json( { error:"Unauthorized" }, { status:HttpStatusCode.Unauthorized } ); } }