본문으로 바로가기

 

Next JS로 프로젝트를 진행하다가 아래와 같은 에러가 발생하였습니다.

page /fetch getServerSideProps can not be attached to a page's component and must be exported from the page

 

 

[에러 원인]

에러 코드를 읽어보시면 확실히 알 수 있지만 번역해보면 page/fetch 스크립트는 getServerSideProps는 페이지 구성 요소에 연결할 수 없으므로 페이지에서 export 해야 한다고 합니다. 아래 코드가 에러가 발생한 코드인데 자세히 보면 export default fetchPanel이 없는 것을 확인할 수 있습니다.

import fetch from 'isomorphic-unfetch';

const fetchPanel = ({user}: any) => {
    const username = user && user.name;
    return <h1>{username}</h1>
}

export const getServerSideProps = async () => {
    try {
        const res: any = await fetch("https://api.github.com/users/cshoon95");

        if (res.status === 200) {
            const user = await res.json();
            return { props: { user }}           
        }

        return { props: {} };
    } catch (error) {
        console.log(error);
        return { props: {} }
    }
}

 

 

[해결 방법]

이 페이지를 export default하면 에러는 해결될 것입니다.

export default fetchPanel;

 

맨 하단에 위의 코드를 추가하였습니다.

import fetch from 'isomorphic-unfetch';

const fetchPanel = ({user}: any) => {
    const username = user && user.name;
    return <h1>{username}</h1>
}

export const getServerSideProps = async () => {
    try {
        const res: any = await fetch("https://api.github.com/users/cshoon95");

        if (res.status === 200) {
            const user = await res.json();
            return { props: { user }}           
        }

        return { props: {} };
    } catch (error) {
        console.log(error);
        return { props: {} }
    }
}

export default fetchPanel;

 

[실행 결과]