Pavindu
Pavindu

Reputation: 3113

How to dynamically configure the runtime for Nextjs API routes

I have deployed my Next.js 13 app on Cloudflare Pages. Since it has a few API routes, I had to export the runtime variable from each route as follows.

export const runtime = "edge"

However, when I do local development, I need to change this to 'nodejs'. Therefore I tried supplying this value through a Next.js environment variable, but it's not working on Cloudflare.

Does anyone know an easier way to toggle between these two runtimes for prod and dev? Thanks in Advance!

Upvotes: 1

Views: 2282

Answers (1)

Em Ha Tuan
Em Ha Tuan

Reputation: 103

I think we can archive your issue by use the .env file to config the variables in production or development. With .env for production and .env.local for development.

Updated: Go to the file next.config.js and add a config:

const nextConfig = {
...
  serverRuntimeConfig: {
    runtime: process.env.RUNTIME
  }
...
}

Now we can use this config with next/config package. Eg.

// /app/pages.tsx

import getConfig from 'next/config';

...
const {serverRuntimeConfig} = getConfig();

console.log(serverRuntimeConfig.runtime); => the value depends on .env or .env.locale file.

It works for me.

Upvotes: 1

Related Questions