From ac30a989f485932c048dd4ce5815b6c61a95a1af Mon Sep 17 00:00:00 2001 From: Shahed Nasser Date: Fri, 6 Sep 2024 12:43:55 +0300 Subject: [PATCH] feat(create-medusa-app): add publishable API key environment variable to Next.js storefront (#9029) When installing with Next.js starter, retrieve the publishable API key seeded and add it to the environment variable in the `.env.local` or `.env.template` file --- .../src/utils/prepare-project.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/cli/create-medusa-app/src/utils/prepare-project.ts b/packages/cli/create-medusa-app/src/utils/prepare-project.ts index 52132141ae..3d2994d452 100644 --- a/packages/cli/create-medusa-app/src/utils/prepare-project.ts +++ b/packages/cli/create-medusa-app/src/utils/prepare-project.ts @@ -234,6 +234,22 @@ export default async ({ }) } + // if installation includes Next.js, retrieve the publishable API key + // from the backend and add it as an enviornment variable + if (nextjsDirectory && client) { + const apiKeys = await client.query( + `SELECT * FROM "api_key" WHERE type = 'publishable'` + ) + + if (apiKeys.rowCount) { + const nextjsEnvPath = path.join(nextjsDirectory, fs.existsSync(path.join(nextjsDirectory, ".env.local")) ? ".env.local" : ".env.template") + + const originalContent = fs.readFileSync(nextjsEnvPath, "utf-8") + + fs.appendFileSync(nextjsEnvPath, originalContent.replace("NEXT_PUBLIC_PUBLISHABLE_KEY=", `NEXT_PUBLIC_PUBLISHABLE_KEY=${apiKeys.rows[0].token}`)) + } + } + displayFactBox({ ...factBoxOptions, message: "Finished Preparation" }) return inviteToken