# Authenticated API

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:

```tsx
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:

```typescript
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 }
    );
  } 
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.shipped.club/features/api-endpoints/authenticated-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
