Switching between Edge and Node.js runtimes

Demonstrate how to specify the Edge runtime for API routes using middleware and how to fall back to the Node.js runtime when necessary.
app.use((req, res, next) => {
  if (shouldUseEdgeRuntime(req)) {
    process.env.NODE_ENV = 'edge';
  } else {
    process.env.NODE_ENV = 'node';
This middleware checks if the current request should use the Edge runtime by calling shouldUseEdgeRuntime function. Depending on the result, it sets the environment variable 'NODE_ENV' to either 'edge' or 'node'. This variable should then be used in other parts of the application to determine which runtime environment to use for specific logic.
const http = require(process.env.NODE_ENV === 'edge' ? 'http' : 'http2');
This line imports either the 'http' module or the 'http2' module depending on the runtime environment. The 'http2' module is often used with Edge runtimes that support HTTP/2, while the 'http' module is the standard for Node.js.
app.get('/api/some-route', (req, res) => {
  if (process.env.NODE_ENV === 'edge') {
    // Handle the request using Edge-specific logic
  } else {
    // Fallback to Node.js-specific logic
In this API route, we make a conditional check on the 'NODE_ENV' environment variable to determine if we should use Edge-specific logic or fallback to the Node.js logic. This practice allows us to distinctly separate and handle behavior for each runtime environment within the same codebase.