Next.js 초기 세팅

신규 프로젝트 Next.js 초기 세팅하는 방법을 알아보겠습니다.

  • next.js ^15

소개

Next.js를 사용해서 신규 프로젝트를 시작할 때 필요한 초기 설정을 알아보겠습니다.

신규 프로젝트 시 자주 사용하는 설정을 정리해두면 향후 프로젝트를 시작할 때 편리합니다.

자주 설정해야하는 반복적인 번거로움을 줄이기 위해 작성하였습니다.

우선 제가 자주 사용하는 설정을 정리해보았습니다.

목차

Next.js 설치

터미널에서 다음 명령어를 실행하여 Next.js를 설치합니다.

npx create-next-app <프로젝트명>

만약 초기 설치시 기본 제공되는 기존 세팅을 제거가 필요하면 -empty 옵션을 추가합니다.

npx create-next-app <프로젝트명> -empty

prettier 설정

prettier는 코드 포맷팅 도구로 코드를 일관된 스타일로 작성할 수 있도록 도와줍니다.

prettier를 파일로 설정 하면 협업하는 동료들과 코드를 일관된 스타일로 작성할 수 있습니다.

우선 prettier 사용시 필요한 패키지를 설치합니다.

pnpm add --save-dev --save-exact prettier

또는 npm을 사용할 경우 다음과 같이 설치합니다.

npm install --save-dev --save-exact prettier

프로젝트 루트 디렉토리에 .prettierrc 파일을 생성하고 다음과 같이 설정합니다.

{
  "semi": true,
  "tabWidth": 2,
  "printWidth": 100,
  "singleQuote": true,
  "jsxSingleQuote": true,
  "trailingComma": "all",
  "bracketSameLine": false,
  "bracketSpacing": true,
  "endOfLine": "lf",
  "arrowParens": "always",
  "plugins": ["prettier-plugin-tailwindcss"]
}

각 옵션은 다음과 같습니다.

  • semi: 세미콜론 사용 여부
  • tabWidth: 탭 너비
  • printWidth: 줄 바꿈 너비
  • singleQuote: 작은 따옴표 사용 여부
  • jsxSingleQuote: JSX에서 작은 따옴표 사용 여부
  • trailingComma: 마지막 쉼표 사용 여부
  • bracketSameLine: 중괄호 위치
  • bracketSpacing: 중괄호 사이 공백 사용 여부
  • endOfLine: 줄 바꿈 문자
  • arrowParens: 화살표 함수 괄호 사용 여부
  • plugins: prettier 플러그인

plugin의 경우 prettier-plugin-tailwindcss를 사용하고 있습니다.

prettier-plugin-tailwindcss는 Tailwind CSS 클래스를 포맷팅할 때 도움을 주고 클래스 이름을 정렬해줍니다.

tailwind를 사용한다면 prettier-plugin-tailwindcss를 사용하는 것을 추천합니다.

설치 방법은 다음과 같습니다.

pnpm add --save-dev prettier-plugin-tailwindcss

또는 npm을 사용할 경우 다음과 같이 설치합니다.

npm install --save-dev prettier-plugin-tailwindcss

prettier 사용시 필요한 설정만 참고하기 위해 .prettierignore 파일을 생성하고 다음과 같이 설정합니다.

node_modules
.next
/out
/public
/dist

robots.ts 설정

robots.ts는 검색 엔진 로봇이 사이트를 방문할 때 어떤 페이지를 수집할지 결정하는 파일입니다.

next.js에서 robots.ts를 사용하면 빌드시 robots.txt 파일을 생성할 수 있습니다.

robots.ts 파일을 프로젝트 /app 디렉토리에 생성하고 다음과 같이 설정합니다.

app/robots.ts
import type { MetadataRoute } from "next";
 
export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: "*",
      allow: "/",
      disallow: "/private/",
    },
    sitemap: "https://recodelog.com/sitemap.xml",
  };
}

robots.ts 파일을 생성하면 빌드시 robots.txt 파일이 생성됩니다.

robots의 옵션은 다음과 같습니다.

  • rules: robots.txt 파일의 규칙
    • userAgent: 사용자 에이전트
    • allow: 허용 경로
    • disallow: 거부 경로
  • sitemap: 사이트맵 파일 경로

robots.txt 파일은 다음과 같이 설정됩니다.

robots.txt
User-agent: *
Allow: /
Disallow: /private/
Sitemap: https://recodelog.com/sitemap.xml

sitemap.ts 설정

sitemap.ts는 사이트맵을 생성하는 파일입니다.

next.js에서 sitemap.ts를 사용하면 빌드시 sitemap.xml 파일을 생성할 수 있습니다.

sitemap.ts 파일을 프로젝트 /app 디렉토리에 생성하고 다음과 같이 설정합니다.

app/sitemap.ts
import type { MetadataRoute } from "next";
 
export default function sitemap(): MetadataRoute.Sitemap {
  return [
    {
      url: "https://recodelog.com",
      lastModified: new Date(),
      changeFrequency: "yearly",
      priority: 1,
    },
    {
      url: "https://recodelog.com/about",
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.8,
    },
    {
      url: "https://recodelog.com/blog",
      lastModified: new Date(),
      changeFrequency: "weekly",
      priority: 0.5,
    },
  ];
}

sitemap.ts 파일을 생성하면 빌드시 sitemap.xml 파일이 생성됩니다.

sitemap의 옵션은 다음과 같습니다.

  • url: URL
  • lastModified: 마지막 수정일
  • changeFrequency: 변경 빈도
  • priority: 우선순위

sitemap.xml 파일은 다음과 같이 설정됩니다.

app/sitemap.xml
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://recodelog.com</loc>
    <lastmod>2025-02-15T00:00:00.000Z</lastmod>
    <changefreq>yearly</changefreq>
    <priority>1</priority>
  </url>
  <url>
    <loc>https://recodelog.com/about</loc>
    <lastmod>2025-02-15T00:00:00.000Z</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.8</priority>
  </url>
  <url>
    <loc>https://recodelog.com/blog</loc>
    <lastmod>2025-02-15T00:00:00.000Z</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>

favicon 및 app icon 설정

favicon은 웹사이트의 아이콘으로 브라우저 탭에 표시됩니다.

next js에서는 파일로 favicon을 설정할 수 있습니다.

/app 폴더에서 apple-icon.png, icon.svg, favicon.ico 파일을 생성해서 사용할 수 있습니다.

자세한 내용은 제가 쓸 글 `Next js 14+ SEO 설정하기 - favicon, icon, apple icon 설정하기`를 참고하세요.

not-found.tsx 설정

404 페이지를 설정하면 사용자가 존재하지 않는 페이지에 접근했을 때 보여줄 페이지를 설정할 수 있습니다.

next.js에서는 not-found.tsx 파일을 생성하면 404 페이지를 설정할 수 있습니다.

/app 폴더에서 not-found.tsx 파일을 생성하고 다음과 같이 설정합니다.

다음 예시는 제 사이트의 404 페이지입니다.

app/not-found.tsx
import { buttonVariants } from "@/components/ui/button";
import Link from "next/link";
import { Metadata } from "next";
 
export const metadata: Metadata = {
  title: "404 - Page Not Found",
  description: "찾으시는 페이지를 찾을 수 없습니다.",
  robots: {
    index: false, // 색인하지 않음
    follow: false, // 링크를 따라가지 않음
  },
};
 
export default function NotFound() {
  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-20 gap-4 bg-gradient-to-br from-black via-gray-800 to-purple-900">
      <h2 className="text-3xl font-bold uppercase text-white">Not Found</h2>
      <p className="text-lg text-center text-gray-300 max-w-md">
        Oops! 찾으시는 페이지를 찾을 수 없습니다. <br />
        입력하신 URL이 정확한지 확인하거나 홈으로 돌아가세요.
      </p>
      <Link href="/" className={buttonVariants({ variant: "outline" })}>
        Home
      </Link>
    </div>
  );
}

not-found.tsx 파일을 생성하면 404 페이지가 설정됩니다.

error.tsx 설정

next.js에서는 error.tsx 파일을 생성하면 에러가 발생했을 때 보여줄 페이지를 설정할 수 있습니다.

/app 폴더에서 error.tsx 파일을 생성하고 다음과 같이 설정합니다.

다음 예시는 제 사이트의 에러 페이지입니다.

app/error.tsx
"use client";
 
import { useEffect } from "react";
 
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  useEffect(() => {
    console.error(error);
  }, [error]);
 
  return (
    <div>
      <h2>에러가 발생했습니다!</h2>
      <button onClick={() => reset()}>재시도</button>
    </div>
  );
}

error.tsx 파일을 생성하면 에러 페이지가 설정됩니다.

결론

Next.js를 사용해서 신규 프로젝트를 시작할 때 필요한 초기 설정을 알아보았습니다.

프로젝트를 시작할 때 필요한 설정을 정리해두면 향후 프로젝트를 시작할 때 편리합니다.

다음 글에서는 Next.js에서 SEO 설정하는 방법을 알아보겠습니다.



관련 태그