Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

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.

Usage

Basic usage

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

Protecting pages using SSR

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 user = userId ? await clerkClient.users.getUser(userId) : undefined; return { props: { ...buildClerkProps(ctx.req, { user }) } }; };

Usage with clerkClient

The clerkClient allows you to access the Clerk API. You can use this to retrieve or update data.

pages/api/example.ts
import { clerkClient } from "@clerk/nextjs"; import { getAuth, buildClerkProps } 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 March 8, 2024

What did you think of this content?

Clerk © 2024