거북이개발자

[Next] ServerSideRendering(SSR) 구현 본문

Next.js

[Next] ServerSideRendering(SSR) 구현

류정식 2021. 3. 9. 14:00

0. 배경

위와 같은 제품 상세페이지를 만들려고 한다.

 

 

 

1. SSR적용 안할시

import axios from 'axios';
import Head from 'next/head';
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react';
import { Loader } from 'semantic-ui-react';
import Item from '../../src/component/Item';

const Post = () => {
    const router = useRouter();
    const { id } = router.query;

    const [item, setItem] = useState({});
    const [isLoading, setIsLoading] = useState(true);

    const API_URL = `http://makeup-api.herokuapp.com/api/v1/products/${id}.json`;

    function getData() {
        axios.get(API_URL).then((res) => {
            setItem(res.data);
        });
    }

    useEffect(()=>{
        if(id&&id>0){
            getData();
        }
    }, [id]);

    return (
        <>
            <Head>
                <title>{item.name}</title>
                <meta name="description" content={item.description}></meta>
            </Head>
            {item && <Item item={item} />}
        </>
    );
};

export default Post;

페이지 소스에 상품의 제품이 나오지 않는 껍데기만 나온다. API를 호출 안 한 상태이다. 이러한 경우 검색엔진에서 불리하다.

 

 

 

 

2. SSR적용

import axios from 'axios';
import Head from 'next/head';
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react';
import { Loader } from 'semantic-ui-react';
import Item from '../../src/component/Item';

const Post = ({item}) => {
   

    return (
        <>
            <Head>
                <title>{item.name}</title>
                <meta name="description" content={item.description}></meta>
            </Head>
            {item && <Item item={item} />}
        </>
    );
};

export default Post;

export async function getServerSideProps(context){
    const id=context.params.id;
    const apiUrl=`http://makeup-api.herokuapp.com/api/v1/products/${id}.json`;
    const res=await axios.get(apiUrl);
    const data=res.data;

    return{
        props:{
            item:data,
        },        
    };
}

getServerSideProps를 적용하였다.

 

이렇게 

페이지 소스에 제품마다의 상세정보가 나오는 걸 볼 수 있다. 검색엔진, SEO, 공유 등에 유리하다.

'Next.js' 카테고리의 다른 글

[Next] Next.js이용한 쇼핑몰 구현  (0) 2021.03.22
[Next] Next 특징  (0) 2021.03.09
Comments