Docs

Endpoints

Clerk provides helpers that allow you to protect your Astro endpoints, fetch the current user, and interact with the Clerk Backend API.

Protect your endpoints

If you aren't protecting your endpoints using clerkMiddleware(), you can use the auth() local and check for the userId value, as shown in the following example:

src/pages/api/route.ts
export async function GET({ locals }) {
  const { userId } = locals.auth()

  if (!userId) {
    return new Response('Error: No signed in user', { status: 401 })
  }

  // Add your Endpoint logic here

  return new Response(JSON.stringify({ userId }))
}

Retrieve data from external sources

Clerk provides integrations with a number of popular databases.

To retrieve a token from a JWT template and fetch data from an external source, use the getToken() method from the auth() local, as shown in the following example:

src/pages/api/route.ts
export async function GET({ locals }) {
  const { userId, getToken } = locals.auth()

  if (!userId) {
    return new Response('Unauthorized', { status: 401 })
  }

  const token = await getToken({ template: 'supabase' })

  // Fetch data from Supabase and return it.
  const data = { supabaseData: 'Hello World' }

  return new Response(JSON.stringify(data))
}

Retrieve the current user

In some cases, you might need the current user in your endpoint. Use the asynchronous currentUser() local to retrieve the current Backend User object, as shown in the following example:

src/pages/api/route.ts
export async function GET({ locals }) {
  const user = await locals.currentUser()

  if (!user) {
    return new Response('Unauthorized', { status: 401 })
  }

  return new Response(JSON.stringify({ user }))
}

Interact with Clerk's Backend API

The JavaScript Backend SDK exposes the Backend API resources and low-level authentication utilities for JavaScript environments.

clerkClient exposes an instance of the JavaScript Backend SDK for use in server environments. Use this instance to interact with the Clerk Backend API, as shown in the following example:

src/pages/api/route.ts
import { clerkClient } from '@clerk/astro/server'

export async function POST(context) {
  const { userId } = context.locals.auth()

  if (!userId) {
    return new Response('Unauthorized', { status: 401 })
  }

  const params = { firstName: 'Clerk', lastName: 'Cookie' }

  const user = await clerkClient(context).users.updateUser(userId, params)

  return new Response(JSON.stringify({ user }))
}

Feedback

What did you think of this content?

Last updated on