You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
redirectToSignIn not respecting publishableKey passed to authMiddleware #1442
I'm using a custom env var naming scheme in order to provide env vars at deploy time.
I am able to supply the publishableKey as a parameter to the middleware,
but when I call redirectToSignIn within afterAuth, I am getting an error:
Server Error
Error: Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
src/middleware.ts (45:40) @ afterAuth
44 | // eslint-disable-next-line @typescript-eslint/no-unsafe-return
> 45 | return redirectToSignIn({
| ^
46 | returnBackUrl: ...,
48 | });
Hello @dcyoung
It seems that custom environment variables for that use case are not currently supported. Let me take a look and provide you with a workaround.
Hello @dcyoung
we are iterating over our API to support this case but currently, I would suggest you try to pass the specific env variable if it's possible. If it's not, I think you could use the draft code below.
// helper.ts - edited copy of packages/nextjs/src/server/redirect.tsimport{constants,redirect}from'@clerk/backend';import{NextResponse}from'next/server';exportconstsetHeader=(res: Response,name: string,val: string)=>{res.headers.set(name,val);returnres;};constredirectAdapter=(url: string)=>{constres=NextResponse.redirect(url);returnsetHeader(res,constants.Headers.ClerkRedirectTo,'true');};exportconst{ redirectToSignIn, redirectToSignUp }=redirect({
redirectAdapter,signInUrl: '<your value if needed>',signUpUrl: '<your value if needed>',publishableKey: '<your value if needed>',});
Hello @kevinmitch14,
The #3001 is not related to redirecToSignIn / redirecToSignUp. The PR attempts to fix issues related to the redirects triggered by the authMiddleware() itself, not the helpers.
Hello @dcyoung ,
We have attempted to solve the current issue in our new major version @clerk/nextjs@v5.0.0-beta.37 (currently in beta). Check the following example:
Hey @dimkl what I've found is that as soon as you pass a custom publishableKey in middleware.
Eg. publishableKey: process.env.CUSTOM_PK_NAME or even hardcoding the publishableKey (publishableKey: "...").
You get the "Error: Missing publishableKey" error. It happens no matter what if you do not use the env variable name NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
I think that the environment variables are not read correctly when they are passed in any way other than the default env variable method used in the docs.
Furthermore, if you pass random values directly into the middleware and also have the ENV vars defined, the ENV vars take precedence over the passed values.
// This will still work if you have NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY defined in env vars.authMiddleware({secretKey: "randomvalue",publishableKey: "randomvalue",})
Hello @dcyoung , We have attempted to solve the current issue in our new major version @clerk/nextjs@v5.0.0-beta.37 (currently in beta). Check the following example:
This still does not work as expected, the same issue persists. Error: @clerk/backend: Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.
If I pass a publishableKey to middleware but also define it as an ENV VAR, it will work because the ENV VAR overrides the passed value. But once I comment out the env var, the issue will come back.
@kevinmitch14 You are correct, there is an issue with the publishableKey and secretKey parameters not being respected. We are looking into this and we will fix the issue with the parameters having priority over the env and avoid raising error when the env are not set for the internal code of the middleware and not for the redirect* helpers.
I would like make clear that the redirectToSignIn() exported helper will not be fixed in the v4 to support the parameters passed to middleware. The helper is deprecated and it's replacement (auth().redirectToSignIn()) will be fixed in v5 version of the @clerk/nextjs package.
The reason is that it requires a breaking change to be fixed, and we can't introduce that in the v4 version.
@nbkhope This issue related to the @clerk/nextjs package and not to the @clerk/clerk-sdk-node. Could you open a separate GH issue for your case and provide a minimal reproduction repo so we could verify that the issue is valid and investigate and assert the fix more quickly? @kevinmitch14 the #3001 fixes fixes the issue of respecting the publishableKey parameter passed in the middleware (eg clerkMiddleware) of @clerk/nextjs, it's to the @clerk/clerk-sdk-node.
@cenobitedk hey thanks for the message. Instead of trying to pass the values with the constructor functions, I ended up letting it automatically detect it as Clerk usually presents in the examples. For that to work, inject my configuration manager values into the required variables into my process.env. Something like the following, before the lines that call ClerkExpressWithAuth:
process.env.CLERK_PUBLISHABLE_KEY = getValueFromSomewhereElseNotInEnvFile();
// ... (repeat for any other necessary variable)
export default clerkMiddleware((auth, req) => {
if (!auth().userId && isProtectedRoute(req)) {
// Add custom logic to run before redirecting
return auth().redirectToSignIn();
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};
I am using clerk with Next JD , i am getting the below error while i am trying to redirect from home page to other protected page
TypeError: auth(...).redirectToSignIn is not a function
Activity
dimkl commentedon Jul 4, 2023
Hello @dcyoung
It seems that custom environment variables for that use case are not currently supported. Let me take a look and provide you with a workaround.
dimkl commentedon Jul 5, 2023
Hello @dcyoung
we are iterating over our API to support this case but currently, I would suggest you try to pass the specific env variable if it's possible. If it's not, I think you could use the draft code below.
I will ping you back when a fix or workaround is available.
clerk-cookie commentedon Aug 4, 2023
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 10 days.
clerk-cookie commentedon Sep 4, 2023
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 10 days.
11 remaining items
dimkl commentedon Mar 27, 2024
Hello @kevinmitch14,
The #3001 is not related to
redirecToSignIn/redirecToSignUp. The PR attempts to fix issues related to the redirects triggered by theauthMiddleware()itself, not the helpers.dimkl commentedon Mar 27, 2024
Hello @dcyoung ,
We have attempted to solve the current issue in our new major version
@clerk/nextjs@v5.0.0-beta.37(currently in beta). Check the following example:kevinmitch14 commentedon Mar 27, 2024
Hey @dimkl what I've found is that as soon as you pass a custom
publishableKeyin middleware.Eg.
publishableKey: process.env.CUSTOM_PK_NAMEor even hardcoding the publishableKey (publishableKey: "...").You get the "Error: Missing publishableKey" error. It happens no matter what if you do not use the env variable name
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.I think that the environment variables are not read correctly when they are passed in any way other than the default env variable method used in the docs.
Furthermore, if you pass random values directly into the middleware and also have the ENV vars defined, the ENV vars take precedence over the passed values.
kevinmitch14 commentedon Mar 27, 2024
This still does not work as expected, the same issue persists.
Error: @clerk/backend: Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.If I pass a
publishableKeyto middleware but also define it as an ENV VAR, it will work because the ENV VAR overrides the passed value. But once I comment out the env var, the issue will come back.dimkl commentedon Mar 28, 2024
@kevinmitch14 You are correct, there is an issue with the publishableKey and secretKey parameters not being respected. We are looking into this and we will fix the issue with the parameters having priority over the env and avoid raising error when the env are not set for the internal code of the middleware and not for the
redirect*helpers.I would like make clear that the
redirectToSignIn()exported helper will not be fixed in the v4 to support the parameters passed to middleware. The helper is deprecated and it's replacement (auth().redirectToSignIn()) will be fixed in v5 version of the@clerk/nextjspackage.The reason is that it requires a breaking change to be fixed, and we can't introduce that in the v4 version.
nbkhope commentedon Apr 21, 2024
I've been trying to pass
publishableKeyto the Express middleware ("@clerk/clerk-sdk-node": "^5.0.0",):but it always appears as empty string when I debug the source code from Clerk at
javascript/packages/sdk-node/src/clerkExpressWithAuth.ts
Lines 5 to 6 in 83ec173
Despite it reading like it would take it as argument.
I don't know what is going on, but I keep getting the following error because of that:
kevinmitch14 commentedon Apr 21, 2024
I think this has been fixed, #3001
dimkl commentedon May 9, 2024
@nbkhope This issue related to the
@clerk/nextjspackage and not to the@clerk/clerk-sdk-node. Could you open a separate GH issue for your case and provide a minimal reproduction repo so we could verify that the issue is valid and investigate and assert the fix more quickly?@kevinmitch14 the #3001 fixes fixes the issue of respecting the
publishableKeyparameter passed in the middleware (eg clerkMiddleware) of@clerk/nextjs, it's to the@clerk/clerk-sdk-node.cenobitedk commentedon May 10, 2024
@nbkhope I've found a way to make it work.
With environment vars
Without environment vars
Simpler version with env vars
nbkhope commentedon May 22, 2024
@cenobitedk hey thanks for the message. Instead of trying to pass the values with the constructor functions, I ended up letting it automatically detect it as Clerk usually presents in the examples. For that to work, inject my configuration manager values into the required variables into my
process.env. Something like the following, before the lines that callClerkExpressWithAuth:brkalow commentedon Oct 15, 2024
Hi all, this should be addressed in our recent versions. Keys passed to
clerkMiddleware()are now respected by auth methods called in your middleware handler. Please see https://clerk.com/docs/references/nextjs/clerk-middleware#dynamic-keys for more information.Divya70 commentedon Nov 3, 2024
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isProtectedRoute = createRouteMatcher([
"/dashboard(.)",
"/meetings(.)",
"/availability(.)",
"/events(.)",
]);
export default clerkMiddleware((auth, req) => {
if (!auth().userId && isProtectedRoute(req)) {
// Add custom logic to run before redirecting
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};
I am using clerk with Next JD , i am getting the below error while i am trying to redirect from home page to other protected page
TypeError: auth(...).redirectToSignIn is not a function
clerk-cookie commentedon Nov 4, 2025
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.