J3D
J3D

Reputation: 108

Missing Publishable Key in AWS Amplify Deployment Despite Setting Environment Variable (Clerk, Next.js)

I'm encountering an issue with deploying my Next.js application using AWS Amplify. My app relies on ClerkProvider for authentication, and I’ve set the NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY environment variable, but I'm getting an error indicating that the publishable key is missing. Please do assist on this!

Note: My application is up and running on Vercel, but I am trying to deploy with AWS Amplify but I kept running into this error.. 😭

Here’s a summary of what I’ve done:

  1. Environment Variable Setup: I have added the NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY environment variable in the AWS Amplify Console under the "Environment Variables" section. I verified that it is set correctly with no extra spaces or typos.

  2. Amplify Build Configuration: My amplify.yml file includes the environment variable setup. Here is the relevant part of the build configuration:

version: 1
applications:
  - appRoot: frontend
    backend:
      phases:
        build:
          commands:
            - echo "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=${NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY}" >> .env
            - npm install
            - npm run build
  1. Root Layout Component In my RootLayout component, I use the environment variable as follows:
import { Inter } from "next/font/google";
import Providers from "./providers";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata = {
  title: "Grapher",
  description: "Visualize your stocks!",
};

export default function RootLayout({ children }) {
  return (
    <ClerkProvider
      afterSignOutUrl="/"
      publishableKey={process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY}
    >
      <html lang="en">
        <body className={inter.className}>
          <Providers>{children}</Providers>
        </body>
      </html>
    </ClerkProvider>
  );
}
  1. Deployment Logs: The cloudwatch deployment logs from AWS Amplify show the following error message related to Clerk:
2024-09-11T16:46:24.465Z
Clerk Trace ID: ${this.clerkTraceId}`),e},
Object.setPrototypeOf(this,e.prototype),this.status=n,this.message=t,this.clerkTraceId=i,this.clerkError=!0,this.errors=function(e=[]){return e.length>0?e.map(tf):[]}(r)}},tm=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});function tv({packageName:e,customMessages:t}){let r=e,n={...tm,...t};function i(e,t){if(!t)return`${r}: ${e}`;let n=e;for(let r of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[r[1]]||"").toString();n=n.replace(`{{${r[1]}}}`,e)}return`${r}: ${n}`}return{setPackageName({packageName:e}){return"string"==typeof e&&(r=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(i(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(i(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(i(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(i(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(i(n.MissingClerkProvider,e))},throw(e){throw Error(i(e))}}}var ty=r(353);async function tb(e,t=1,r=5){try{return await e()}catch(i){var n;if(t>=r)throw i;return await (n=2**t*100,new Promise(e=>setTimeout(e,n))),tb(e,t+1,r)}}var tw=e=>"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e).toString("base64"):e,t_=[".lcl.dev",".lclstage.dev",".lclclerk.com"],tS=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],tk=[".lcl.dev","lclstage.dev",".lclclerk.com",".accounts.lclclerk.com"],tx=[".accountsstage.dev"],tT="https://api.clerk.com",tE="pk_live_";function tC(e,t={}){if(!(e=e||"")||!function(e){let t=(e=e||"").startsWith(tE)||e.startsWith("pk_test_"),r=eY(e.split("_")[2]||"").endsWith("$");return t&&r}(e)){if(t.fatal)throw Error("Publishable key not valid.");return null}let r=e.startsWith(tE)?"production":"development",n=eY(e.split("_")[2]);return n=n.slice(0,-1),t.proxyUrl?n=t.proxyUrl:"development"!==r&&t.domain&&(n=`clerk.${t.domain}`),{instanceType:r,frontendApi:n}}function tO(e){return e.startsWith("test_")||e.startsWith("sk_test_")}async function tR(e,t=globalThis.crypto.subtle){let r=new TextEncoder().encode(e);return tw(String.fromCharCode(...new Uint8Array(await t.digest("sha-1",r)))).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}var tP=(e,t)=>`${e}_${t}`,tI=()=>!1,tN=()=>{try{return!0}catch(e){}return!1},tA=new Set,tM=(e,t,r)=>{let n=tI()||tN(),i=null!=r?r:e;tA.has(i)||n||(tA.add(i),console.warn(`Clerk - DEPRECATION WARNING: "${e}" is deprecated and will be removed in the next major release.

2024-09-11T16:46:24.465Z
Error: @clerk/nextjs: Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.

2024-09-11T16:46:24.465Z
at Object.throwMissingPublishableKeyError (/tmp/app/.next/server/middleware.js:17:161

Upvotes: 2

Views: 343

Answers (2)

Leckan
Leckan

Reputation: 1

Ensure the environment variables are added correctly and update the key names in the build command as below. See Making environment variables accessible to server-side runtimes for more details.

build:
      commands:
        - env | grep -e NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY >> .env.production
        - env | grep -e CLERK_SECRET_KEY >> .env.production
        - npm run build

Upvotes: 0

Med Agou
Med Agou

Reputation: 1281

Is this a monorepo folder the snippet from amplify.yaml doesn't provide much infos? if so you need to prefix your commands with the approot folder, somthing like this from the docs :

        - env | grep -e NEXT_PUBLIC_ >> <approot>/<app1>/.env

Of course adapt your .env files and paths as required.

Upvotes: 0

Related Questions