Search…
Get started with Next.js API
This guide will help you authenticate requests made to your Next.js API routes.

0. Pre-requirements

This guide assumes you have properly completed your Next.js frontend setup.

1. Set CLERK_API_KEY

Create a file named .env.local in your application root if it doesn't exist already. Any variables inside this file will be accessible in your backend with process.env.VARIABLE_NAME.
Make sure you update this variable with the API key found in your dashboard under Settings API Keys.
.env.local
1
CLERK_API_KEY=test_asdf1234
Copied!

2. Use the @clerk/nextjs/api

The @clerk/nextjs package comes with all the Next.js API methods for using Clerk exported at @clerk/nextjs/api.
1
/** Next.js API imports for Clerk. */
2
import { ... } from "@clerk/nextjs/api";
Copied!

3. Create an API route

In Next.js, API routes are created by adding a file to the pages/api folder. The filename is used as the API path. New Next.js applications come with a pages/api/hello.js file that we can edit.
pages/api/hello.js
1
import { requireSession } from "@clerk/nextjs/api";
2
3
export default requireSession((req, res) => {
4
res.statusCode = 200;
5
res.json({ id: req.session.userId });
6
});
Copied!
That's it! Now, if a user is signed in, requests to /api/hello will return that user's ID. This ID will never change for this user, so you can use it as a stable user ID in your own codebase.
If a user is signed out, the requireSession helper will automatically return with HTTP status 401 and no response body. If you'd prefer to process a request when there is no user, try the withSession helper instead:
pages/api/hello.js
1
import { withSession } from "@clerk/nextjs/api";
2
3
export default withSession((req, res) => {
4
res.statusCode = 200;
5
if (req.session){
6
res.json({ id: req.session.userId });
7
} else {
8
res.json({ id: null });
9
}
10
});
Copied!
Last modified 1mo ago