NextJS에서 sitemap 자동 생성

저는 개별 도메인으로 직접 클라우드 상에서 운영하고 있는 홈페이지가 있습니다. 구글 검색 노출이 잘 되지 않아서 구글 서치 콘솔에 sitemap 등록하는 방법을 알아보겠습니다.

일단 구글링 해보면 여러 가지 방법이 있는데 저는 간단한 패키지를 이용하여 sitemap을 만드는 법을 소개합니다.

구글 서치 콘솔 (GSC)

구글 서치 콘솔은 구글 검색 엔진에서 웹사이트를 검색 결과에 표시하고 관리하는 데 도움을 주는 도구입니다. 이는 웹사이트 소유자와 웹마스터들이 그들의 웹사이트가 어떻게 인덱싱되고 검색 결과에 표시되는지 추적하고 최적화할 수 있도록 돕는 도구입니다. 이를 통해 웹사이트의 검색 엔진 최적화 (SEO)를 개선하고 사용자 경험을 향상시킬 수 있습니다. 구글 서치 콘솔을 사용하면 다음과 같은 기능을 수행할 수 있습니다:

웹사이트 성능 모니터링: 웹사이트가 구글 검색 결과에서 어떻게 표시되는지 추적하고 이해합니다.

인덱싱 현황 확인: 구글이 웹사이트의 페이지를 어떻게 인덱싱하고 있는지 확인할 수 있습니다.

검색어 분석: 사용자가 웹사이트를 어떤 검색어로 찾았는지 확인하고 해당 검색어의 성능을 분석할 수 있습니다.

링크 상태 확인: 다른 웹사이트에서의 링크를 모니터링하여 백링크 프로파일을 관리합니다.

사이트맵 제출: 사이트맵을 제출하여 구글이 웹사이트를 빠르게 인덱싱할 수 있도록 도와줍니다.

이러한 기능들을 통해 웹사이트의 검색 엔진 최적화를 개선하고 구글 검색 결과에서 더 높은 순위를 달성할 수 있습니다.

NextJs

1. next-sitemap 설치

먼저 next-sitemap 패키지를 설치합니다. 우리는 production 배포 시 자동생성 시킬 것이므로 -dev 옵션을 생략합니다.

yarn add next-sitemap
next-sitemap
Sitemap generator for next.js. Latest version: 4.2.3, last published: a year ago. Start using next-sitemap in your project by running `npm i next-sitemap`. There are 42 other projects in the npm registry using next-sitemap.

 

next-sitemap


next-sitemap은 Next.js 프레임워크에서 사용할 수 있는 사이트 맵(Sitemap) 생성 도구입니다. 사이트 맵은 검색 엔진에 웹사이트의 페이지 구조를 알려줌으로써 검색 엔진 크롤러가 사이트를 더 효율적으로 탐색하고 인덱싱할 수 있도록 도와줍니다.

일반적으로 Next.js 프로젝트에서 사이트 맵을 생성하려면 페이지 구조와 URL을 수동으로 정의해야 합니다. 그러나 next-sitemap을 사용하면 이 작업을 자동화할 수 있습니다. 이 도구를 사용하면 Next.js 프로젝트의 페이지를 기반으로 사이트 맵을 생성하고 정의할 수 있습니다. next-sitemap을 사용하는 주요 이점은 다음과 같습니다:

자동화된 사이트 맵 생성: Next.js 프로젝트의 페이지를 기반으로 사이트 맵을 자동으로 생성합니다.
동적 라우트 지원: 동적으로 생성되는 페이지나 라우트도 사이트 맵에 포함될 수 있습니다.
사용자 정의 옵션 제공: 사용자는 필요에 따라 사이트 맵을 생성하는 데 사용되는 다양한 옵션을 사용자 정의할 수 있습니다.
SEO 개선: 생성된 사이트 맵을 통해 검색 엔진이 웹사이트를 더 효율적으로 탐색하고 인덱싱할 수 있습니다.

이러한 이유로 next-sitemap은 Next.js 기반의 프로젝트에서 SEO를 개선하고 검색 엔진 최적화에 도움을 주는 중요한 도구 중 하나입니다.

2. config 파일 생성 및 수정

next-sitemap.config.js을 만들고 아래와 같이 작성합니다.

/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'https://example.com',
  generateRobotsTxt: true, // (optional)
  // ...other options
}

package.json에 스크립트를 추가합니다.

{
  "build": "next build",
  "postbuild": "next-sitemap"
}

export 명령에 next-sitemap이 실행되도록 수정합니다.

"export": "next build && next-sitemap && next export",

3. 세부 옵션 설정

next-sitemap.config.js에서 세부 설정을 수정할 수 있습니다.

property description type
siteUrl Base url of your website string
output (optional) Next.js output modes. Check documentation. standalone, export
changefreq (optional) Change frequency. Default daily string
priority (optional) Priority. Default 0.7 number
sitemapBaseFileName (optional) The name of the generated sitemap file before the file extension. Default "sitemap" string
alternateRefs (optional) Denote multi-language support by unique URL. Default [] AlternateRef[]
sitemapSize(optional) Split large sitemap into multiple files by specifying sitemap size. Default 5000 number
autoLastmod (optional) Add <lastmod/> property. Default true true
exclude (optional) Array of relative paths (wildcard pattern supported) to exclude from listing on sitemap.xml or sitemap-*.xml. e.g.: ['/page-0', '/page-*', '/private/*'].
Apart from this option next-sitemap also offers a custom transform option which could be used to exclude urls that match specific patterns
string[]
sourceDir (optional) next.js build directory. Default .next string
outDir (optional) All the generated files will be exported to this directory. Default public string
transform (optional) A transformation function, which runs for each relative-path in the sitemap. Returning null value from the transformation function will result in the exclusion of that specific path from the generated sitemap list. async function
additionalPaths (optional) Async function that returns a list of additional paths to be added to the generated sitemap list. async function
generateIndexSitemap Generate index sitemaps. Default true boolean
generateRobotsTxt (optional) Generate a robots.txt file and list the generated sitemaps. Default false boolean
robotsTxtOptions.transformRobotsTxt (optional) Custom robots.txt transformer function. (Example: custom-robots-txt-transformer)

Default: async(config, robotsTxt)=> robotsTxt
async function
robotsTxtOptions.policies (optional) Policies for generating robots.txt.

Default:
[{ userAgent: '*', allow: '/' }]
IRobotPolicy[]
robotsTxtOptions.additionalSitemaps (optional) Options to add additional sitemaps to robots.txt host entry string[]
robotsTxtOptions.includeNonIndexSitemaps (optional) From v2.4x onwards, generated robots.txt will only contain url of index sitemap and custom provided endpoints from robotsTxtOptions.additionalSitemaps.

This is to prevent duplicate url submission (once through index-sitemap -> sitemap-url and once through robots.txt -> HOST)

Set this option true to add all generated sitemap endpoints to robots.txt

Default false (Recommended)
 






출처: https://inodyssey.tistory.com/14 [인사이트 오디세이:티스토리]