0
0
NextJSframework~5 mins

Edge runtime vs Node.js runtime in NextJS

Choose your learning style9 modes available
Introduction

Edge runtime and Node.js runtime are two ways Next.js runs your code. They help your app work fast and in different places.

When you want your app to respond very quickly to users around the world.
When you need to run code close to the user, like showing location-based content.
When your code needs full Node.js features like file system access.
When you want to run server code that needs more time or complex tasks.
When you want to use modern web APIs available in the browser environment.
Syntax
NextJS
export const runtime = 'edge'; // or 'nodejs'
Use 'edge' to run code on the Edge runtime, which is faster and closer to users.
Use 'nodejs' to run code on the Node.js runtime, which supports more Node features.
Examples
This example sets the runtime to Edge and returns a simple response.
NextJS
export const runtime = 'edge';

export async function GET() {
  return new Response('Hello from Edge!');
}
This example uses Node.js runtime to fetch data from an API and return it.
NextJS
export const runtime = 'nodejs';

export async function GET() {
  const data = await fetch('https://api.example.com/data');
  return new Response(JSON.stringify(await data.json()));
}
Sample Program

This Next.js API route runs on the Edge runtime. It sends a quick text response to the user.

NextJS
export const runtime = 'edge';

export async function GET() {
  return new Response('Fast response from Edge runtime!');
}
OutputSuccess
Important Notes

The Edge runtime runs your code in a lightweight environment close to users worldwide.

Node.js runtime supports more features but runs on traditional servers, which may be slower for global users.

Choose Edge runtime for speed and Node.js runtime for full Node features.

Summary

Edge runtime runs code near users for faster responses.

Node.js runtime supports full Node features but may be slower globally.

Set the runtime using export const runtime = 'edge' or 'nodejs'.