neondatabase / preview-branches-with-vercel

Example project that shows how you can create a branch for every preview deployment on Vercel using GitHub actions
29 stars 11 forks source link

Preview branches and next.js middleware #25

Closed sarahc-dev closed 6 months ago

sarahc-dev commented 6 months ago

Steps to reproduce

The steps in this blog post worked until I start using Next.js middleware. I have tried removing the middleware.ts file and it works again. For some reason, it appears that it is not able to use DATABASE_URL from .env and is trying to force it from Vercel Environment Variables. If I have no DATABASE_URL set for preview in Vercel, I get the following: Error: No database connection string was provided to neon(). Perhaps an environment variable has not been set? If I set it, it is using this URL instead.

I have also tried manually setting DATABASE_URL inside the created .vercel/.env.preview.local file with no success.

Expected result

To be able to create preview branches when using middleware.

Actual result

500: INTERNAL_SERVER_ERROR
Code: EDGE_FUNCTION_INVOCATION_FAILED

Is it possible to create preview branches in Vercel whilst using middleware?

sarahc-dev commented 6 months ago

After writing this out, I have managed to solve the issue.

I realised that environment variables in .env* files are not made available to Edge Runtime, unless their name is prefixed with NEXTPUBLIC

I'm not sure if this is the best way but I resolved it by adding the created branch as NEXT_PUBLIC_DATABASE_URL= instead of DATABASE_URL= in .env and conditionally setting the connectionString in my database file

let connectionString = process.env.DATABASE_URL

if (process.env.VERCEL_ENV === "preview" && process.env.NEXT_PUBLIC_DATABASE_URL) {
  connectionString = process.env.NEXT_PUBLIC_DATABASE_URL
}

const sql = neon(connectionString!)