Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.devGet API keys

Handling requests with Next.js

Next.js API Route

In Next.js, the withAuth and requireAuth helper functions can be used in your API routes to access the authenticated user.

1
import { withAuth } from '@clerk/nextjs/api';
2
3
export default withAuth((req, res) => {
4
const { userId } = req.auth;
5
6
if (userId){
7
res.status(200).json({ id: userId });
8
} else {
9
res.status(401).json({ id: null });
10
}
11
});

Using getServerSideProps (SSR)

Next.js uses special export named getServerSideProps to enable server-side rendering. The withServerSideAuth Clerk helper provides access to the auth state.

1
import { withServerSideAuth } from "@clerk/nextjs/ssr";
2
3
export const getServerSideProps = withServerSideAuth(({ req, resolvedUrl }) => {
4
const { sessionId } = req.auth;
5
6
if (!sessionId) {
7
return { redirect: { destination: "/sign-in?redirect_url=" + resolvedUrl } };
8
}
9
10
return { props: {} };
11
});

Using Edge Middleware

If you're using Edge Functions you can restrict access to a page using the Clerk edge middleware auth helper as shown below:

1
import { withEdgeMiddlewareAuth } from "@clerk/nextjs/edge-middleware";
2
import { NextResponse } from "next/server";
3
4
export default withEdgeMiddlewareAuth((request) => {
5
const { sessionId } = request.auth;
6
7
if (!sessionId) {
8
const destination = request.nextUrl.href;
9
const url = request.nextUrl.clone();
10
url.pathname = "/sign-in";
11
url.searchParams.set("redirect_url", destination);
12
return NextResponse.redirect(url);
13
}
14
15
return NextResponse.next();
16
});
17

Was this helpful?

Clerk © 2022