본문 바로가기

프론트엔드/Next.js

Next.js SEO plugin 이용하기(feat. next-seo, next-sitemap)

반응형
  • 키워드: next-seo, next-sitemap, SEO, robots.txt, sitemap, canonical URL
  • 상황
    • 지금까지는 Next.js 프로젝트에서 _document.tsx와 next/head를 이용하여 meta/link tag를 작성했다.
    • next-seo 라는 패키지를 이용해서 더 간단하고 가독성있게 SEO 관련 설정을 하고자 한다.
  • 해결 과정
      1. next-seo 패키지를 설치한다.
        (https://www.npmjs.com/package/next-seo)
          yarn add next-seo


      2. 먼저 seo.config.js 파일을 생성하고, 모든 페이지에서 사용할 전역(Default) SEO properties를 작성한다.
        설명을 위해 사이트 이름 등은 'example'로 한다.
          // seo.config.js
        export default {
          titleTemplate: '%s | Example',
          additionalLinkTags: [
            {
              rel: 'icon',
              href: '/favicon.ico',
            },
            {
              rel: 'manifest',
              href: '/manifest.json',
            },
            ...
          ],
          additionalMetaTags: [
            {
              name: 'theme-color',
              content: '#FFFFFF',
            },
            ...
          ],
          openGraph: {
            type: 'website',
            site_name: 'Example',
            images: [{ url: 'https://example.com/example_square_image.png' }],
          },
        };

        'additionalLinkTags'와 'additionalMetaTags' option 덕분에 _document.tsx를 작성할 필요가 없어진다.

        'openGraph' option에서는 OG meta tag와 관련된 설정을 할 수 있다. 이 때, og:title과 og:description은 각각 'title', 'description', option이 설정되어 있을 경우 생략할 수 있다.(각각의 값으로 자동으로 채워짐) description과 og:url 값은 3번 과정에서 각 페이지별로 설정할 예정이므로 생략한다.
        'titleTemplate'은 3번 과정에서 설정할 title option과 관련이 있으므로 일단 넘어간다.

        이렇게 설정한 'DefaultSEO'를 _app.tsx에서 import하여 전역 SEO 설정을 마무리한다.
          // _app.tsx
        import type { AppProps } from 'next/app';
        ...
        import { DefaultSeo } from 'next-seo';
        import SEO from '../config/seo.config';
        ...
        
        function MyApp({ Component, pageProps }: AppProps) {
          ...
          
          return (
            <>
              <DefaultSeo {...SEO} />
              <Component {...pageProps} />
              ...
            </>
          );
        }
        export default MyApp;


      3. 전역 SEO 설정을 마쳤으니, 이제 페이지별로 설정을 할 차례이다. 먼저 index.tsx 파일(메인 페이지)로 이동하여 'NextSeo'를 import한다.
          // _app.tsx
        ...
        import { NextSeo } from 'next-seo';
        
        const Home: NextPage = () => {
          ...
        
          return (
            <>
              <NextSeo
                title="home"
                description="home description"
                canonical="https://example.com"
                openGraph={{
                  url: 'https://example.com',
                }}
              />
        
              <main>
                ...
              </main>
            </>
          );
        };
        export default Home;

        2번 과정에서 설정하지 않은 title, description, canonical, og:url을 설정한다.

        title="home"으로 작성할 경우, DefaultSEO에 설정해 둔 titleTemplate('%s | Example')과 결합하여 최종 page title은 'home | Example' 이 된다.

        각 페이지는 중복 페이지도 아니고, 독립적인 페이지이니 canonical과 og:url을 'https://example.com/path'와 같은 형식으로 채우면 된다.
        (canonical(선호 URL)가 생소하다면 아래 링크를 통해 내용을 확인할 수 있다.
        https://searchadvisor.naver.com/guide/markup-structure)


        마찬가지로 index.tsx 이외의 다른 페이지들도 작성한다.
           // another.tsx
        ...
        import { NextSeo } from 'next-seo';
        
        const Another: NextPage = () => {
          return (
            <>
              <NextSeo
                title="another"
                description="another description"
                canonical="https://example.com/another"
                openGraph={{
                  url: 'https://example.com/another',
                }}
              />
        
              <main>
                ...
              </main>
            </>
          );
        };
        
        export default Another;

        이제 프로젝트를 빌드하면, head tag안의 SEO 관련 tag들이 잘 작성되어 있음을 알 수 있다.
        SEO 관련 tags
      4. 네이버 웹 페이지 최적화 도구에서 SEO 관련 설정이 잘 되어있는지 확인할 수 있다. vegimap project로 체크해 본 결과 모든 검사를 통과하는 것을 확인했다!
        네이버 웹 페이지 최적화 검사
  • 한 걸음 더
        1. sitemap을 직접 작성하는 것은 번거로운 작업이기 때문에, build할 때 자동으로 sitemap을 만들어주는 next-sitemap도 소개하고자 한다. (https://www.npmjs.com/package/next-sitemap)

        2. 먼저 패키지를 설치한다.
            yarn add next-sitemap

          그 후, project root 바로 아래에 'next-sitemap.js' 파일을 만든다.
          /** @type {import('next-sitemap').IConfig} */
          
          module.exports = {
            siteUrl: process.env.NEXT_PUBLIC_URL || 'https://example.com',
            generateRobotsTxt: true,
          };

          마지막으로 build 시 next-sitemap을 실행하도록 스크립트를 설정한다.
            // package.json
          "scripts": {
            "build": "next build",
            "postbuild": "next-sitemap"
          }


        3. 이제 yarn build로 프로젝트를 빌드하면, public 폴더 아래에 robots.txt, sitemap.xml 파일이 자동으로 생성되는 것을 확인할 수 있다!

robots.txt, sitemap.xml

반응형