Node.js Runtime과 Edge Runtime의 비교

SteadySlower·2024년 12월 18일
0

NextJS

목록 보기
2/5
post-thumbnail

Next.js의 middleware는 Edge runtime에서 실행된다는 것을 알게 되었다. 이번 기회에 Edge runtime과 Node.js Runtime에 대해서 정리해보겠다.


1. Node.js Runtime (기본적인 javascript 실행 환경)

Node.js Runtime에서는 모든 Next.js API Routes가 기본적으로 실행된다. Node.js의 모든 모듈과 데이터베이스 연결이 가능하다.

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

export default async function handler(req, res) {
  // PrismaClient를 사용한 데이터베이스 조회
  const users = await prisma.user.findMany()

  res.status(200).json({ 
    message: "Node.js Runtime 사용", 
    data: users 
  })
}

특징:

  • 데이터베이스 연결 혹은 file system 같은 무거운 작업이 가능하다.
  • 복잡한 비즈니스 로직 처리에 적합하다.

2. Edge Runtime (가벼운 실행 환경)

Edge Runtime은 Node.js Runtime에 비해 가볍고 빠른 실행 환경이다. 그 댓가로 Edge Runtime에서는 Node.js의 일부 기능이 제한된다.

예를 들어 유저의 정보를 찾기 위해서 db를 참고할 수 없고 아래처럼 쿠키를 활용해야 한다.

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // 요청 URL 검사
  const isLoggedIn = request.cookies.get('auth')
  
  if (!isLoggedIn) {
    return NextResponse.redirect(new URL('/login', request.url))
  }
  
  return NextResponse.next()
}

특징:

  • 서버리스 실행으로 빠른 응답이 가능하다.
  • 인증, 리다이렉션 등 간단한 처리에 적합하다.
  • 클라이언트와 가까운 엣지 서버에서 실행되어 지연 시간이 최소화된다.
profile
백과사전 보다 항해일지(혹은 표류일지)를 지향합니다.

0개의 댓글