Next.jsNext.js 기초강의 8개 중 7번째난이도 기초

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

발행 읽는 시간 약 1 분

  • Next.js
  • Vercel
  • 배포
  • 환경변수
  • 프로덕션

강의 소개

환경 변수를 안전하게 관리하고, Vercel로 Next.js 앱을 배포하는 방법을 배웁니다. 도메인 연결, 환경별 설정, Edge Runtime도 이해합니다.

환경 변수#

Bash
# .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 클라이언트 환경 변수#

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

// 클라이언트에서 사용 가능: NEXT_PUBLIC_ 접두사
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;   // ✅ 어디서나
// 단, 빌드 시 번들에 포함됨 → 비밀 정보 금지
TSX
// 서버 컴포넌트에서 환경 변수 유효성 검사
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 배포#

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

# 2. 로그인
vercel login

# 3. 배포 (처음)
vercel

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

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


Vercel 환경 변수 설정#

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

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

next.config.js 설정#

JavaScript
/** @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에서 실행해 더 빠른 응답을 제공합니다.

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

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

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

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


빌드 최적화#

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

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

정리#

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

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

Follow · Ask · Work

이 글이 도움이 됐다면

짧은 작업 기록과 데모는 인스타그램에 올립니다. 만들고 싶은 것이 있다면 프로젝트 의뢰나 협업 제안도 편하게 보내 주세요.

글쓴이

파란여우

직접 만든 AI 앱·제품의 개발·배포를 공개하는 실전형 테크 크리에이터

파란여우 소개 Instagram @bluefox._.hi

이어서 보기

만들고 싶은 것이 있다면 프로젝트 의뢰로 알려 주세요.