콘텐츠로 이동

Netlify

사용되는 기술

  • 정적 사이트 호스팅 및 JAMstack 배포
  • Serverless Functions (AWS Lambda 기반)
  • CDN (Content Delivery Network)
  • Git 기반 지속적 배포

프로젝트 개요

Netlify는 정적 사이트와 JAMstack 애플리케이션을 위한 클라우드 플랫폼입니다. 무료로 100GB 용량, 빌드 300분까지 사용 가능하며, SSL 인증서 자동 제공과 CI/CD 구축이 가능합니다.

React 프로젝트 배포 방법

1. Netlify 회원가입 및 설정

  1. Netlify 사이트에서 GitHub 계정으로 회원가입
  2. Import from Git 클릭
  3. GitHub 저장소 연결 및 권한 설정
    • 특정 저장소만 선택 또는 모든 저장소 선택 가능
  4. 배포할 저장소 선택

2. 배포 설정

  • Branch to deploy: master 또는 main
  • Base directory: 프로젝트 루트 (빈칸으로 두면 됨)
  • Build command: npm run build
  • Publish directory: build
  • Environment variables: 필요시 환경변수 설정

3. 배포 실행

  • Deploy 버튼 클릭
  • Production deploys에서 배포 상황 확인
  • 완료 후 Overview에서 사이트 미리보기 확인

핵심 문제 해결법

React Router 새로고침 404 오류 해결

React는 SPA(Single Page Application)이므로 새로고침 시 서버에서 해당 경로를 찾을 수 없어 404 오류가 발생합니다.

해결법 1: netlify.toml 파일 사용

파일 위치: 프로젝트 루트 (package.json과 같은 위치)

toml

[build]
  command = "npm run build"
  publish = "build"

[redirects](redirects)
  from = "/*"
  to = "/index.html"
  status = 200

해결법 2: _redirects 파일 사용

파일 위치: public 폴더 내

/* /index.html 200

빌드 오류 해결

Build script returned non-zero exit code: 2

이 오류는 주로 다음과 같은 이유로 발생합니다:

  1. 환경변수 누락
  2. 의존성 문제
  3. 빌드 스크립트 오류

해결법:

json

// package.json 확인
{
  "scripts": {
    "build": "react-scripts build"
  }
}

환경변수 설정:

  • Site settings → Environment variables
  • REACT_APP_ 접두사가 붙은 변수들 추가

고급 설정

netlify.toml 전체 설정 예시

toml

[build]
  command = "npm run build"
  functions = "netlify/functions"
  publish = "build"

[build.environment]
  NODE_VERSION = "18"
  NPM_VERSION = "8"

# 리다이렉트 설정
[redirects](redirects)
  from = "/api/*"
  to = "/.netlify/functions/:splat"
  status = 200

[redirects](redirects)
  from = "/*"
  to = "/index.html"
  status = 200

# 헤더 설정
[headers](headers)
  for = "/*"
  [headers.values]
    X-Frame-Options = "DENY"
    X-XSS-Protection = "1; mode=block"
    Content-Security-Policy = "default-src 'self'"

# 브랜치별 설정
[context.production]
  command = "npm run build:prod"

[context.deploy-preview]
  command = "npm run build:preview"

[context.branch-deploy]
  command = "npm run build:dev"

_redirects 파일 고급 설정

# SPA 라우팅 (가장 중요)
/* /index.html 200

# API 프록시
/api/* https://api.example.com/:splat 200

# 301 리다이렉트
/old-page /new-page 301

# 조건부 리다이렉트 (국가별)
/blog/* /kr/blog/:splat 302 Country=kr

# 역할 기반 리다이렉트
/admin/* /login 302 Role=!admin

도메인 및 HTTPS 설정

1. 도메인 변경

  1. Site settings → Domain management
  2. Domain settings 클릭
  3. Edit site name으로 서브도메인 변경 가능
  4. Add custom domain으로 구매한 도메인 연결

2. 자동 HTTPS

  • Let's Encrypt 인증서 자동 발급
  • Force HTTPS 옵션 자동 활성화
  • 별도 설정 불필요

Serverless Functions 활용

함수 생성 및 사용

디렉토리 구조:

project/
├── netlify/
│   └── functions/
│       ├── hello.js
│       └── api.js
├── src/
├── public/
└── netlify.toml

함수 예시:

javascript

// netlify/functions/hello.js
exports.handler = async (event, context) => {
  const { name } = event.queryStringParameters || {};

  return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      message: `Hello ${name || 'World'}!`
    })
  };
};

프론트엔드에서 호출:

javascript

fetch('/.netlify/functions/hello?name=John')
  .then(response => response.json())
  .then(data => console.log(data));

환경변수 관리

1. Netlify 대시보드에서 설정

  • Site settings → Environment variables
  • Key-Value 형태로 추가

2. 브랜치별 환경변수

toml

[context.production.environment]
  REACT_APP_API_URL = "https://api.production.com"

[context.deploy-preview.environment]
  REACT_APP_API_URL = "https://api.staging.com"

3. 보안 고려사항

  • REACT_APP_ 접두사가 붙은 변수는 클라이언트에 노출됨
  • 민감한 정보는 Serverless Functions에서 처리

성능 최적화

1. 빌드 최적화

toml

[build]
  command = "CI=false npm run build"  # 경고를 오류로 처리하지 않음

[build.environment]
  NODE_OPTIONS = "--max_old_space_size=4096"  # 메모리 증가

2. 캐싱 설정

toml

[headers](headers)
  for = "/static/*"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

[headers](headers)
  for = "/*.js"
  [headers.values]
    Cache-Control = "public, max-age=31536000, immutable"

모니터링 및 디버깅

1. 배포 로그 확인

  • Deploys 탭에서 실시간 로그 확인
  • 빌드 실패 시 상세 오류 메시지 제공

2. 함수 로그

  • Functions 탭에서 서버리스 함수 실행 로그 확인

3. 분석 도구

  • Analytics에서 방문자 통계 확인
  • 성능 메트릭 모니터링

일반적인 문제 해결

1. 빌드 시간 초과

  • 불필요한 의존성 제거
  • 빌드 스크립트 최적화
  • 캐시 활용

2. 이미지 최적화

javascript

// React에서 이미지 최적화
import { useState, useEffect } from 'react';

const OptimizedImage = ({ src, alt }) => {
  const [imageSrc, setImageSrc] = useState('');

  useEffect(() => {
    // Netlify Large Media 또는 외부 이미지 최적화 서비스 사용
    setImageSrc(`${src}?nf_resize=fit&w=800`);
  }, [src]);

  return <img src={imageSrc} alt={alt} loading="lazy" />;
};

3. SEO 최적화

javascript

// React Helmet 사용
import { Helmet } from 'react-helmet';

const App = () => (
  <>
    <Helmet>
      <title>My App</title>
      <meta name="description" content="App description" />
      <meta property="og:title" content="My App" />
    </Helmet>
    {/* 앱 컨텐츠 */}
  </>
);