본문 바로가기

개발 공부/React

Next.js에서 메타 태그와 Open Graph 태그를 동적으로 관리하는 방법

메타 태그

메타 태그는 웹 페이지의 정보를 담는 HTML 태그입니다.

<head> 영역에 작성되며, 사용자에게 직접 보이지 않지만 검색 엔진 최적화(SEO)에 핵심적인 역할을 합니다.

주요 메타 태그 종류

  • <title>: 브라우저 탭이나 검색 엔진 제목에 사용됨
  • <meta name="description">: 검색 결과 설명에 표시됨
  • <meta name="viewport">: 반응형 웹 디자인을 위한 뷰포트 설정
  • <meta name="robots">: 검색엔진 크롤러 설정 (ex. noindex, nofollow)

예시

<head>
  <title>나의 멋진 블로그</title>
  <meta name="description" content="프론트엔드 개발 지식을 나누는 블로그입니다." />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

 


 

Open Graph

Open Graph Protocol은 페이스북에서 시작되어, SNS 플랫폼에서 링크를 공유할 때 제목, 설명, 이미지 등 미리보기 정보를 제어할 수 있는 태그입니다.

주요 OG 태그

  • og:title: 링크의 제목
  • og:description: 링크 설명
  • og:image: 썸네일 이미지
  • og:url: 링크 주소
  • og:type: 콘텐츠 타입 (website, article 등)
  • og:site_name: 사이트 이름

예시

<meta property="og:title" content="나의 멋진 블로그 글 제목" />
<meta property="og:description" content="이 글은 Next.js에서 메타 태그를 다루는 법을 설명합니다." />
<meta property="og:image" content="https://example.com/images/og-image.png" />
<meta property="og:url" content="https://example.com/blog/nextjs-meta-tags" />

OG 태그를 설정하지 않으면 SNS 공유 시 잘못된 제목이나 이미지가 뜰 수 있습니다.

 
 

Next.js에서 메타 태그와 OG 태그를 다루는 법

Next.js는 next/head 컴포넌트를 통해 페이지마다 동적으로 <head> 내용을 구성할 수 있습니다.

1. 정적인 메타 태그 설정

import Head from 'next/head';

export default function Home() {
  return (
    <>
      <Head>
        <title>홈페이지 | MySite</title>
        <meta name="description" content="Next.js 프로젝트 홈입니다." />
        <meta property="og:title" content="홈페이지 | MySite" />
        <meta property="og:description" content="Next.js 프로젝트의 OG 설명입니다." />
        <meta property="og:image" content="/og-image.png" />
        <meta property="og:url" content="https://mysite.com" />
      </Head>
      <main>홈 콘텐츠</main>
    </>
  );
}

2. 동적으로 메타 태그 설정 (블로그 포스트 예시)

// pages/blog/[slug].tsx
import Head from 'next/head';
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const slug = ctx.params?.slug;
  const res = await fetch(`https://api.mysite.com/posts/${slug}`);
  const post = await res.json();

  return { props: { post } };
};

export default function BlogPost({ post }: { post: any }) {
  return (
    <>
      <Head>
        <title>{post.title} | MySite 블로그</title>
        <meta name="description" content={post.description} />
        <meta property="og:title" content={post.title} />
        <meta property="og:description" content={post.description} />
        <meta property="og:image" content={post.thumbnailUrl} />
        <meta property="og:url" content={`https://mysite.com/blog/${post.slug}`} />
      </Head>
      <article>
        <h1>{post.title}</h1>
        <div>{post.content}</div>
      </article>
    </>
  );
}

3. 공통 메타 태그는 _app.tsx에서 설정

// pages/_app.tsx
import Head from 'next/head';
import type { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charSet="UTF-8" />
        <meta property="og:site_name" content="MySite" />
      </Head>
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

 

 

next-seo 라이브러리

next-seo는 반복적인 SEO 설정을 편리하게 해주는 라이브러리입니다.

일반적으로 페이지마다 Head를 작성할 때 생기는 중복을 줄이고, 선언형 방식으로 SEO 정보를 구성할 수 있습니다.

장점

  • SEO 설정을 컴포넌트처럼 재사용 가능
  • Open Graph, Twitter, canonical 등 다양한 SEO 요소 지원
  • 사이트 전체 공통 설정도 가능 (defaultSeo)

설치

npm install next-seo

사용 예시

import { NextSeo } from 'next-seo';

export default function Page() {
  return (
    <>
      <NextSeo
        title="SEO 제목"
        description="SEO 설명"
        openGraph={{
          url: 'https://mysite.com/page',
          title: 'OG 제목',
          description: 'OG 설명',
          images: [
            {
              url: 'https://mysite.com/og-image.jpg',
              width: 800,
              height: 600,
              alt: '썸네일',
            },
          ],
          site_name: 'MySite',
        }}
      />
      <main>페이지 내용</main>
    </>
  );
}

 

기본 설정 파일로 전역 기본값 설정

// next-seo.config.ts
const defaultSeoConfig = {
  titleTemplate: '%s | MySite',
  defaultTitle: 'MySite',
  description: 'MySite 공식 웹사이트입니다.',
  openGraph: {
    type: 'website',
    locale: 'ko_KR',
    url: 'https://mysite.com',
    site_name: 'MySite',
    images: [
      {
        url: 'https://mysite.com/default-og.jpg',
        width: 1200,
        height: 630,
        alt: '기본 OG 이미지',
      },
    ],
  },
};

export default defaultSeoConfig;
// _app.tsx
import { DefaultSeo } from 'next-seo';
import defaultSeoConfig from '../next-seo.config';

function MyApp({ Component, pageProps }) {
  return (
    <>
      <DefaultSeo {...defaultSeoConfig} />
      <Component {...pageProps} />
    </>
  );
}

export default MyApp;

 

정리

  • 메타 태그는 검색 엔진 최적화(SEO) 에 중요합니다.
  • Open Graph 태그는 SNS 공유 미리보기에 필수입니다.
  • Next.js에서는 next/head로 쉽게 커스터마이징 가능하고,
  • 동적 라우팅이나 데이터 기반 페이지에서도 유연하게 사용할 수 있습니다.
  • next-seo를 사용하면 더 간편하게 관리할 수 있습니다.