Next.jsNext.js 기초 · 7기초

환경 변수와 배포 — Vercel로 프로덕션 배포

Next.jsVercel배포환경변수프로덕션

환경 변수

# .env.local (로컬 개발, .gitignore에 포함)
DATABASE_URL=postgresql://localhost:5432/mydb
OPENAI_API_KEY=sk-...
AUTH_SECRET=my-secret

# .env.production (프로덕션 전용)
DATABASE_URL=postgresql://prod-server/mydb

서버 vs 클라이언트 환경 변수

// 서버 전용 (브라우저에 노출 안 됨)
const apiKey = process.env.OPENAI_API_KEY;    // ✅ 서버에서만
const dbUrl = process.env.DATABASE_URL;       // ✅ 서버에서만

// 클라이언트에서 사용 가능: NEXT_PUBLIC_ 접두사
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;   // ✅ 어디서나
// 단, 빌드 시 번들에 포함됨 → 비밀 정보 금지
// 서버 컴포넌트에서 환경 변수 유효성 검사
function validateEnv() {
    const required = ["DATABASE_URL", "AUTH_SECRET", "OPENAI_API_KEY"];
    const missing = required.filter(key => !process.env[key]);
    if (missing.length) {
        throw new Error(`환경 변수 누락: ${missing.join(", ")}`);
    }
}

Vercel 배포

# 1. Vercel CLI 설치
npm install -g vercel

# 2. 로그인
vercel login

# 3. 배포 (처음)
vercel

# 4. 프로덕션 배포
vercel --prod

또는 GitHub 저장소를 Vercel에 연결하면 push 시 자동 배포됩니다.


Vercel 환경 변수 설정

Vercel 대시보드 → Settings → Environment Variables에서 설정:

DATABASE_URL      = postgresql://...   [Production, Preview, Development]
OPENAI_API_KEY    = sk-...             [Production]
AUTH_SECRET       = ...                [All environments]

next.config.js 설정

/** @type {import('next').NextConfig} */
const nextConfig = {
    // 환경별 설정
    env: {
        APP_VERSION: process.env.npm_package_version,
    },

    // 리다이렉트
    async redirects() {
        return [
            {
                source: "/old-path",
                destination: "/new-path",
                permanent: true,  // 301
            },
        ];
    },

    // 헤더
    async headers() {
        return [
            {
                source: "/(.*)",
                headers: [
                    { key: "X-Frame-Options", value: "DENY" },
                    { key: "X-Content-Type-Options", value: "nosniff" },
                ],
            },
        ];
    },
};

module.exports = nextConfig;

Edge Runtime

일반 Node.js 대신 Edge에서 실행해 더 빠른 응답을 제공합니다.

// 미들웨어는 기본으로 Edge에서 실행

// API Route에서 Edge 사용
export const runtime = "edge";

export async function GET(request: Request) {
    return Response.json({ message: "Edge에서 실행" });
}

제약: Node.js API 사용 불가 (파일 시스템, 네이티브 모듈 등)


빌드 최적화

# 빌드 분석
npm install @next/bundle-analyzer
// next.config.js
const withBundleAnalyzer = require("@next/bundle-analyzer")({
    enabled: process.env.ANALYZE === "true",
});

module.exports = withBundleAnalyzer(nextConfig);
ANALYZE=true npm run build

정리

항목설명
.env.local로컬 전용, git 제외
NEXT_PUBLIC_클라이언트 노출 가능 환경 변수
VercelNext.js 공식 호스팅, 자동 배포
Edge RuntimeCDN 엣지에서 실행, 빠른 응답
환경 변수 검증시작 시 필수값 확인

다음 편에서는 Next.js 실전 프로젝트 — 데이터베이스와 인증을 갖춘 풀스택 앱을 만듭니다.

궁금한 점이 있으신가요?

협업·의뢰는 아래로, 가벼운 소통은 인스타그램 @bluefox._.hi도 환영이에요.