Edge API Routes (Beta)

Edge API Routes enable you to build high performance APIs with Next.js. Using the Edge Runtime, they are often faster than Node.js-based API Routes. This performance improvement does come with constraints, like not having access to native Node.js APIs. Instead, Edge API Routes are built on standard Web APIs.

Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won’t increase your client-side bundle size.

Examples

Basic

  1. export const config = {
  2. runtime: 'experimental-edge',
  3. }
  4. export default (req) => new Response('Hello world!')

JSON Response

  1. import type { NextRequest } from 'next/server'
  2. export const config = {
  3. runtime: 'experimental-edge',
  4. }
  5. export default async function handler(req: NextRequest) {
  6. return new Response(
  7. JSON.stringify({
  8. name: 'Jim Halpert',
  9. }),
  10. {
  11. status: 200,
  12. headers: {
  13. 'content-type': 'application/json',
  14. },
  15. }
  16. )
  17. }

Cache-Control

  1. import type { NextRequest } from 'next/server'
  2. export const config = {
  3. runtime: 'experimental-edge',
  4. }
  5. export default async function handler(req: NextRequest) {
  6. return new Response(
  7. JSON.stringify({
  8. name: 'Jim Halpert',
  9. }),
  10. {
  11. status: 200,
  12. headers: {
  13. 'content-type': 'application/json',
  14. 'cache-control': 'public, s-maxage=1200, stale-while-revalidate=600',
  15. },
  16. }
  17. )
  18. }

Query Parameters

  1. import type { NextRequest } from 'next/server'
  2. export const config = {
  3. runtime: 'experimental-edge',
  4. }
  5. export default async function handler(req: NextRequest) {
  6. const { searchParams } = new URL(req.url)
  7. const email = searchParams.get('email')
  8. return new Response(email)
  9. }

Forwarding Headers

  1. import { type NextRequest } from 'next/server'
  2. export const config = {
  3. runtime: 'experimental-edge',
  4. }
  5. export default async function handler(req: NextRequest) {
  6. const authorization = req.cookies.get('authorization')
  7. return fetch('https://backend-api.com/api/protected', {
  8. method: req.method,
  9. headers: {
  10. authorization,
  11. },
  12. redirect: 'manual',
  13. })
  14. }

Differences between API Routes

Edge API Routes use the Edge Runtime, whereas API Routes use the Node.js runtime.

Edge API Routes can stream responses from the server and run after cached files (e.g. HTML, CSS, JavaScript) have been accessed. Server-side streaming can help improve performance with faster Time To First Byte (TTFB).

View the supported APIs and unsupported APIs for the Edge Runtime.