Next.js buildClerkProps() buildClerkProps
Clerk uses buildClerkProps
to inform the client-side helpers of the authentication state of the user. This function is used SSR in the getServerSideProps
function of your Next.js application.
pages /myServerSidePage import { getAuth , buildClerkProps } from '@clerk/nextjs/server'
import { GetServerSideProps } from 'next'
export const getServerSideProps : GetServerSideProps = async (ctx) => {
const { userId } = getAuth ( ctx .req)
if ( ! userId) {
// handle user is not signed in.
}
// Load any data your application needs for the page using the userId
return { props : { ... buildClerkProps ( ctx .req) } }
}
It is important to protect your API routes to ensure that only authenticated users can access them. You can do this by checking if the userId
is present in the getAuth()
response.
pages /api /example.ts import { clerkClient , getAuth , buildClerkProps } from '@clerk/nextjs/server'
import { GetServerSideProps } from 'next'
export const getServerSideProps : GetServerSideProps = async (ctx) => {
const { userId } = getAuth ( ctx .req)
const client = await clerkClient ()
const user = userId ? await client . users .getUser (userId) : undefined
return { props : { ... buildClerkProps ( ctx .req , { user }) } }
}
The clerkClient
allows you to access the Clerk API. You can use this to retrieve or update data.
pages /api /example.ts import { getAuth , buildClerkProps , clerkClient } from '@clerk/nextjs/server'
import { GetServerSideProps } from 'next'
export const getServerSideProps : GetServerSideProps = async (ctx) => {
const { userId } = getAuth ( ctx .req)
const user = userId ? await clerkClient (). users .getUser (userId) : undefined
return { props : { ... buildClerkProps ( ctx .req , { user }) } }
}
Last updated on Nov 18, 2024