Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

Backend Requests

Overview

If you are using Next.js or Express with Node.js, Clerk provides middleware that sets the session property for easy access and can also require a session be available.

Next.js Serverless API Route

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

import { withAuth } from '@clerk/nextjs/api';
export default withAuth((req, res) => {
const { userId } = req.auth;
if (userId){
res.status(200).json({ id: userId });
} else {
res.status(401).json({ id: null });
}
});

Gatsby Functions

The Gatsby Function uses the requireAuth helper function from the Node SDK directly.

import { requireAuth } from '@clerk/clerk-sdk-node';
// `requireAuth` automatically throws an
// error when no user session is found.
export default requireAuth((req, res) => {
res.status(200).json({ id: req.auth.userId })
})

Node.js and Express Middleware

Both the above-mentioned withAuth and requireAuth functions are available in the Node SDK. There are also exports available specifically for Express. You can read more about the Express middleware here.

Go Middleware

The Clerk Go SDK provides a simple middleware that adds the active session to the request’s context. You can see an example code implementation in Go here.

Rack Middleware for Ruby on Rails

The Clerk Ruby SDK comes with Rack middleware to lazily load the Clerk session and user. If added as a gem to Rails application, the Clerk::Authenticatable concern can be added to your controller. Learn more about how to integrate Clerk with Rack and Rails.

Manual Authentication

If there is not middleware available for your preferred language or framework, you can extract the session token manually. For same origin requests, the session token is included in the __session cookie and you can use an open source library to parse the cookie on the back-end. For cross-origin requests, the Bearer token inside the Authorization header contains the session token. You can read more about validating the session token for additional information.

Was this helpful?

Clerk © 2023