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 isAuthenticated value, as shown in the following example:
export async function GET({ locals }) {
const { isAuthenticated, userId } = locals.auth()
if (!isAuthenticated) {
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:
export async function GET({ locals }) {
const { isAuthenticated, userId, getToken } = locals.auth()
if (!isAuthenticated) {
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:
export async function GET({ locals }) {
const user = await locals.currentUser()
if (!user) {
return new Response('Unauthorized', { status: 401 })
}
return new Response(
JSON.stringify({ userId: user.id, email: user.emailAddresses[0].emailAddress }),
)
}Interact with Clerk's Backend API
clerkClient is a wrapper around the Backend API that makes it easier to interact with the API for JavaScript environments. For example, here's how you can use clerkClient to update a user's first and last name:
import { clerkClient } from '@clerk/astro/server'
export async function POST(context) {
// Use the `auth()` local to access the `Auth` object
// https://clerk.com/docs/reference/backend/types/auth-object
const { isAuthenticated, userId } = context.locals.auth()
// Protect the endpoint from unauthenticated users
if (!isAuthenticated) {
return new Response('Unauthorized', { status: 401 })
}
// Set the parameters for the `updateUser()` method
const params = { firstName: 'Clerk', lastName: 'Cookie' }
// Use the `updateUser()` method to update the user's first and last name
const user = await clerkClient(context).users.updateUser(userId, params)
// Return the updated user
return new Response(JSON.stringify({ user }))
}Feedback
Last updated on