Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

withClerkMiddleware() (deprecated)

withClerkMiddleware() was deprecated and will be removed in the next major version (Core 2). Please use authMiddleware() for now. Note that authMiddleware() will also be removed in the next major version in favor of clerkMiddleware()(opens in a new tab).

The withClerkMiddleware wrapper allows Clerk to access session data on the server side allowing you to use any of our server side helpers without any additonal network calls.

Usage

Basic usage

This is the minimal amount of code needed to use Clerk Server Side helpers.

middleware.ts
import { withClerkMiddleware } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; export default withClerkMiddleware((req: NextRequest) => { return NextResponse.next(); }); // Stop Middleware running on static files export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - _next * - static (static files) * - favicon.ico (favicon file) * - public folder */ "/((?!static|.*\\..*|_next|favicon.ico).*)", "/", ], }

Usage with page protection

middleware.ts
import { withClerkMiddleware } from "@clerk/nextjs/server"; import { getAuth } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; // Set the paths that don't require the user to be signed in const publicPaths = ["/", "/sign-in*", "/sign-up*"]; const isPublic = (path: string) => { return publicPaths.find((x) => path.match(new RegExp(`^${x}$`.replace("*$", "($|/)"))) ); }; export default withClerkMiddleware((request: NextRequest) => { if (isPublic(request.nextUrl.pathname)) { return NextResponse.next(); } // if the user is not signed in redirect them to the sign in page. const { userId } = getAuth(request); if (!userId) { // redirect the users to /pages/sign-in/[[...index]].ts const signInUrl = new URL("/sign-in", request.url); signInUrl.searchParams.set("redirect_url", request.url); return NextResponse.redirect(signInUrl); } return NextResponse.next(); }); export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - _next * - static (static files) * - favicon.ico (favicon file) * - public folder */ "/((?!static|.*\\..*|_next|favicon.ico).*)", "/", ], }

Last updated on March 7, 2024

What did you think of this content?

Clerk © 2024