NEXT.JS 서버 펫칭 방법

악음·2023년 5월 26일
0

NEXTJS

목록 보기
1/1
post-thumbnail

next.js의 pre-Rendering 방식

  1. Static Gerneration(Recommended): Build Time에 HTML파일을 미리 생성해둠
  2. Server-side Rendering : 매 요청마다 HTML을 생성함

Static Generation

  • sg 방식은 프로젝트 빌드시에 data-fething 메서드를 호출하는 방식이다 따라서 해당 방식으로 pre-rendering 된 페이지는 정적(static)이며 CDN에 캐시될 수 있기에 빠른 퍼포먼스를 제공한다.
  • 이때 생성되는 정적페이지는 외부 데이터들도 포함시킬수 있고 Client-side에서 가능하다

종합하자면 빌드시에 페이지를 미리생성=> 더빠른 퍼포먼스
이후 cliend-side를 통해 외부 데이터들도 포함가능

SG 메소드들

  • getStaticProps
    • 해당 매소드는 pre-render 될 컴포넌트에 props으로 데이터를 전달한다
    • 하지만 빌드 시점에서 호출된 데이터이므로 빈번히 응답값이 바뀌는 api를 pre-fetch하기에는 부적합
    • 예시 코드
   function Blog({ posts }) {
  	// Render posts...
    }
	// This function gets called at build time
export async function getStaticProps() {
  	// Call an external API endpoint to get posts
  	const res = await fetch('https://.../posts')
  	const posts = await res.json()
	  // By returning { props: { posts } }, the Blog component
  	  // will receive `posts` as a prop at build time
  	return {
	    props: {
    		  posts,
    		},
  	}
  }
export default Blog
  • getStaticPaths
    • next js 는 다이나믹 라우트를 재공한다 (/posts/[id].js)
      getStaticPaths는 이러한 동적인 라우트에 포함되는 데이터를 결정해준다.
    • 예시코드
// This function gets called at build time
	export async function getStaticPaths() {
 		// Call an external API endpoint to get posts
		const res = await fetch('https://.../posts')
  		const posts = await res.json()

 		 // Get the paths we want to pre-render based on posts
  		const paths = posts.map((post) => ({
    			params: { id: post.id },
     		}))

  		// We'll pre-render only these paths at build time.
  		// { fallback: false } means other routes should 404.
  		return { paths, fallback: false }
	} 

또한 getStaticPaths에서 전달한 path를 getStaticProps에서 사용할수 있다.

function Post({ post }) {
 // Render post...
}

export async function getStaticPaths() {
 // ...
}

// This also gets called at build time
export async function getStaticProps({ params }) {
 // params contains the post `id`.
 // If the route is like /posts/1, then params.id is 1
 const res = await fetch(`https://.../posts/${params.id}`)
 const post = await res.json()

 // Pass post data to the page via props
 return { props: { post } }
}

export default Post

Server-side Rendering

  • SSR을 사용하는 페이지는 매 요청시마다 page HTML이 생성된다 때문에 Data 가 빈번하게 바뀌는 경우에 적합하다.

getServerSideProps

  • 사용 및 동작은 getStaticProps와 유사하다. 다만 호출될 때가 빌드시점인지, 페이지 요청 시점인지가 다르다.
  • 예시코드
function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

getInitialProps (권장하지 않음)

  • 권장하지 않는 방식이다. 왜그럴까?
  • getServerSideProps처럼 페이지 요청때마다 함수가 호출된다.
function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

Page.getInitialProps = async (ctx) => {
  const res = await fetch('https://api.github.com/repos/vercel/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default Page
  • 처음 호출시 서버에서 fetching을 시작하고 이후 useRouter, Link으로 페이지 이동시 Client에서 fetchign 한다
  • 문제는 여기서 발생하는데 외부 모듈을 사용할경우 처음호출시 server 불러와서 사용할땐 괜찮지만 client에서 사용할경우에 해당 모듈이 같이 내려와서 사용하기떄문에 대기시간이 길어질수 있는 side-effect가 있다.
  • 장점 client에서 data fetching할경우 서버부담을 줄일수있다
  • 단정 외부모듈 사용시 지연시간이 발생할수있다.

ASO(Automatic Static Optimization)지원여부

위에 말했듯이 정적페이지는 pre-render가 가능한 (getStaticProps,getStaticPaths,혹은 아무것도 없는 콤포넌트)에서만 지원한다.

profile
RN/react.js개발자이며 배운것들을 제가 보기위해서 정리하기 때문에 비속어 오타가 있을수있습니다.

0개의 댓글