Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

Next.js(React)에서 JSON-LD 데이터 렌더링하는 방법 완벽 가이드

Next.js를 비롯한 다양한 React 프로젝트에서 JSON-LD(application/ld+json) 스키마를 제대로 동작시키는 방법을 단계별로 알아보겠습니다.

렌더링에 필요한 세 가지 요소

Next.js 또는 그 외 모든 React 앱에서 JSON-LD 데이터를 렌더링하려면 아래 세 가지를 활용해야 합니다.

  • <script> 요소
  • dangerouslySetInnerHTML 속성
  • JSON.stringify 메서드(직렬화용)

JSON-LD란?

JSON-LD는 'JavaScript Object Notation for Linked Data'의 약자로, 웹사이트 콘텐츠에 대한 Schema.org 데이터를 검색 엔진에 전달하는 가볍고 효율적인 방식입니다. 구글 등 주요 검색 엔진이 페이지의 의미를 더 정확하게 이해하도록 도와주기 때문에 SEO 최적화에서 중요한 역할을 합니다.

그럼 실제 예제를 통해 구현 과정을 살펴보겠습니다.

1단계: JSON-LD 객체 준비하기

먼저 HTML 형태로 작성된 JSON-LD 스키마가 있다고 가정해 보겠습니다.

<script type="application/ld+json">
{
  "@context": "https://schema.org/", 
  "@type": "Product", 
  "name": "Name of service",
  "image": "https://somewebsite.com/static/images/some-image.jpg",
  "description": " I seek the means to fight injustice. To turn fear against those who prey on the fearful. Someone like you. Someone who'll rattle the cages. My anger outweighs my guilt.",
  "brand": "Company Name",
  "review": {
    "@type": "Review",
    "name": "Company Name ",
    "reviewBody": "It was a dog. It was a big dog. It's not who I am underneath but what I do that defines me. Well, you see... I'm buying this hotel and setting some new rules about the pool area.",
    "reviewRating": {
      "@type": "Rating",
      "ratingValue": "5"
    },
    "datePublished": "2020-04-06",
    "author": {"@type": "Person", "name": "Emma"}
  }
}
</script>

이 스키마를 Next.js에서 사용하려면 첫 번째로, HTML <script> 태그를 제거하고 순수한 JSON-LD 객체만 남겨야 합니다.

두 번째로, 해당 객체를 하나의 변수에 할당합니다.

const schemaData = 
{
  "@context": "https://schema.org/", 
  "@type": "Product", 
  "name": "Name of service",
  "image": "https://somewebsite.com/static/images/some-image.jpg",
  "description": "I seek the means to fight injustice. To turn fear against those who prey on the fearful. Someone like you. Someone who'll rattle the cages. My anger outweighs my guilt.",
  "brand": "Company Name",
  "review": {
    "@type": "Review",
    "name": "Company Name ",
    "reviewBody": "It was a dog. It was a big dog. It's not who I am underneath but what I do that defines me. Well, you see... I'm buying this hotel and setting some new rules about the pool area.",
    "reviewRating": {
      "@type": "Rating",
      "ratingValue": "5"
    },
    "datePublished": "2020-04-06",
    "author": {"@type": "Person", "name": "Emma"}
  }
}

2단계: JSON.stringify()로 직렬화하기

이제 schemaData 변수를 JSON.stringify() 메서드로 직렬화해야 합니다.

JSON.stringify(schemaData)

3단계: dangerouslySetInnerHTML로 렌더링하기

마지막으로 <script> 요소 안에서 dangerouslySetInnerHTML 속성의 값으로 JSON.stringify(schemaData)를 전달하면, 브라우저에서 정상적으로 렌더링됩니다.

<script
    type="application/ld+json"
    dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }}
  />

완성된 페이지 예제

아직 개념이 잘 잡히지 않았다면, 위 과정을 모두 적용한 완전한 페이지 예제를 참고하세요. 이 코드는 모든 Next.js/React 웹사이트에서 그대로 사용할 수 있습니다.

import React from 'react';

const schemaData = 
{
  "@context": "https://schema.org/", 
  "@type": "Product", 
  "name": "Name of service",
  "image": "https://somewebsite.com/static/images/some-image.jpg",
  "description": "I seek the means to fight injustice. To turn fear against those who prey on the fearful. Someone like you. Someone who'll rattle the cages. My anger outweighs my guilt.",
  "brand": "Company Name",
  "review": {
    "@type": "Review",
    "name": "Company Name ",
    "reviewBody": "It was a dog. It was a big dog. It's not who I am underneath but what I do that defines me. Well, you see... I'm buying this hotel and setting some new rules about the pool area.",
    "reviewRating": {
      "@type": "Rating",
      "ratingValue": "5"
    },
    "datePublished": "2020-04-06",
    "author": {"@type": "Person", "name": "Emma"}
  }
}

const SomePage = () => {
  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }}
      />
      <div>Your content</div>
    </>
  );
};

export default SomePage;

추가 팁

React는 기본적으로 XSS(Cross-Site Scripting) 공격을 방지하기 위해 innerHTML 직접 조작을 권장하지 않습니다. 하지만 JSON-LD처럼 신뢰할 수 있는 정적 데이터를 삽입할 때는 dangerouslySetInnerHTML이 표준적인 해결 방법입니다. 다만 사용자 입력값을 그대로 삽입하지 않도록 항상 주의하세요.