authMiddleware()
The authMiddleware()
helper integrates Clerk authentication into your Next.js application through middleware. authMiddleware()
is compatible with both the App and Pages routers.
Usage
Create a middleware.ts
file. If your application uses the src/
directory, your middleware.ts
file should be placed inside the src/
folder. If you are not using a src/
directory, place the middleware.ts
file in your root directory.
With the recommended matcher, all routes are protected by Clerk's authentication middleware, with the exception of internal /_next/
routes and static files. Static files are detected by matching on paths that end in .+\..+
. If your middleware needs to run on all routes but you don't want Clerk to protect every route, use the ignoredRoutes
option.
Default behaviour
If there is no afterAuth
present in the middleware, then authMiddleware()
will fall back to its default behavior:
- If the
.env
based settings for the sign-in and sign-up routes are present, add the sign-in and sign-up routes to any routes listed inpublicRoutes
. - If the
.env
based settings are not present, add/sign-in
and/sign-up
to any routes listed inpublicRoutes
. - Make all routes from
publicRoutes
public. - Configure all routes from
ignoredRoutes
to be ignored and return no auth related information. - Make all remaining routes protected.
Example
Assuming that the .env
based settings for sign-in and sign-up are set to /sign-in
and /sign-up
respectively, the following authMiddleware()
would make the routes /
, /contact
, /sign-in
and /sign-up
public, no routes ignored, and all remaining routes protected.
Use afterAuth()
for fine-grained control
Some developers will need to handle specific cases such as handling redirects differently or detecting if a user is inside an organization. These cases can be handled with afterAuth()
.
Understanding afterAuth
configuration
When using afterAuth
, the checks must handle all cases — a custom afterAuth
completely overrides the default behavior covered earlier, aside from adding sign-in and sign-up to publicRoutes
. afterAuth
does not allow you to add just one check and rely on the default behavior otherwise.
Looking at the example immediately above, the following is happening:
- Redirect all users who are not signed in but who are visiting a protected page to the sign-in route.
- If the user is signed in but is not currently active in an organization and is not visiting the route for selecting an organization, then redirect them to the organization selector. This will force users to select and be active in an organization to visit other parts of the site.
- If the user is signed in and accessing a protected route, allow them to access it.
- If none of the above match, then the user is visiting a public route. Allow them to. Don't check if they are signed in -- it doesn't matter.
Use beforeAuth()
to execute middleware before authentication
If you need additional middleware handlers to execute before Clerk's authentication middleware, use beforeAuth()
. An example where the middleware handler from next-intl
is executed can be seen below.
Make routes public by using publicRoutes
By default, Clerk's authMiddleware()
treats all routes as private if the middleware runs. If you need to make specific routes public, use the publicRoutes
option.
Use the req
object to match against urls. The following example makes all routes but /dashboard
public.
You can also use regex to match routes. The following is an example of a negative assertion that makes only the /admin
route protected.
If you are building your own sign in pages, you don't need to add these pages to your publicRoutes
. They will be inferred from your .env
file:
Execution order of beforeAuth
, publicRoutes
, and afterAuth
If you define an afterAuth
function, it will run even if the request corresponds to a private route and no user is signed in. If you don’t define an afterAuth
function, a redirect response to the signInUrl
will be returned automatically. This diagram explains how and when the two handlers are invoked in the runtime.
Debug your middleware
If you are having issues getting your Middleware dialed in, or are trying to narrow down auth-related issues, you can use the debugging feature in authMiddlware
. Add debug: true
to authMiddlware
and you will get debug logs in your terminal.
Options
The authMiddleware()
method accepts an optional object. The following options are available:
- Name
afterAuth?
- Type
function
- Description
Called after the authentication middleware is executed. This function has access to the
Auth
object and can be used to execute logic based on the auth state.
- Name
apiRoutes?
- Type
string[]
- Description
A list of routes that should return 401 if the user is not signed in. You can use glob patterns to match multiple routes or a function to match against the request object. For example:
['/foo', '/bar(.*)']
or[/^\/foo\/.*$/]
- Name
audience?
- Type
string | string[]
- Description
A string or list of audiences.
- Name
audience?
- Type
string | string[]
- Description
A string or list of audiences. If passed, it is checked against the
aud
claim in the token.
- Name
authorizedParties?
- Type
string[]
- Description
An allowlist of origins to verify against, to protect your application from the subdomain cookie leaking attack.
For example:['http://localhost:3000', 'https://example.com']
For more information, refer to the reference guide.
- Name
beforeAuth?
- Type
function
- Description
A function called before the authentication middleware is executed. If a redirect response is returned, the middleware will respect it and redirect the user. If
false
is returned, the auth middleware will not execute and the request will be handled as if the auth middleware was not present.
- Name
clockSkewInSeconds? (deprecated)
- Type
number
- Description
Deprecated in favor of
clockSkewInMs
.
- Name
clockSkewInMs?
- Type
number
- Description
Specifies the allowed time difference (in milliseconds) between the Clerk server (which generates the token) and the clock of the user's application server when validating a token. Defaults to 5000 ms (5 seconds).
- Name
debug?
- Type
boolean
- Description
Enables debugging mode in the Clerk middleware handler. Logs out additional debugging information.
- Name
domain?
- Type
string
- Description
The domain used for satellites to inform Clerk where this application is deployed.
- Name
isSatellite?
- Type
boolean
- Description
When using Clerk's satellite feature, this should be enabled for secondary domains.
- Name
proxyUrl?
- Type
string
- Description
If using a proxy, specify the URL of the proxy.
- Name
jwksCacheTtlInMs?
- Type
number
- Description
Set the JWKs cache TTL, in milliseconds.
- Name
jwtKey?
- Type
string
- Description
An optional custom JWT key to use for session token validation.
- Name
ignoredRoutes?
- Type
string[]
- Description
A list of routes that should be ignored by the middleware. This list typically includes routes for static files or Next.js internals. For improved performance, these routes should be skipped using the default config.matcher instead.
- Name
publicRoutes?
- Type
string[]
- Description
A list of routes that should be accessible without authentication. You can use glob patterns to match multiple routes or a function to match against the request object. For example:
['/foo', '/bar(.*)']
or[/^\/foo\/.*$/]
The sign in and sign up URLs are included by default, unless a function is provided.
- Name
publishableKey?
- Type
string
- Description
An alternate Clerk publishable key.
- Name
secretKey?
- Type
string
- Description
An alternate Clerk secret key.
- Name
signInUrl?
- Type
string
- Description
An alternative sign in URL.
- Name
skipJwksCache?
- Type
boolean
- Description
Disables use of the JWKs cache.
- Name
apiKey?
- Type
string
- Description
An alternate Clerk API key.
- Name
frontendApi?
- Type
string
- Description
An alternate Clerk frontend API URL.
Feedback
Last updated on