[낙서 #8] 2022년 1월 30일

낙서·2022년 1월 30일
0

낙서

목록 보기
8/22

Next.js

API Routes

Next.js는 API endpoint를 Node.js serverless function으로 쉽게 만들 수 있도록 API Routes를 지원한다.

Creating API Routes

API Routes는 Next.js app 안에서 API endpoint를 만들 수 있도록 해준다.
pages/api 폴더에 다음과 같은 형식의 함수를 만들면 된다.

// req = HTTP incoming message, res = HTTP server response
export default function handler(req, res) {
  // ...
}

이것들은 Serverless Function들로 deploy 될 수 있다. (Lambdas라고도 부른다)

Creating a simple API endpoint

pages/api 경로에 hello.js 파일을 만들고 다음 코드를 입력하면 http://localhost:3000/api/hello에서 {"text":"Hello"}를 볼 수 있다.

export default function handler(req, res) {
  res.status(200).json({ text: 'Hello' })
}

req는 http.IncomingMessage, res는 http.ServerResponse

API Routes Details

Do not fetch API Route from getStaticProps or getStaticPaths

API Route를 getStaticPropsgetStaticPaths 에서 fetch 하지 말아야한다.
대신 server-side 코드를 getStaticPropsgetStaticPaths 안에 직접 작성하여 사용해야 한다.
getStaticProps or getStaticPaths 이 서버 사이드에서만 동작하기 때문에 클라이언트 사이드에서는 실행되지 않는다.
브라우저를 위한 JS bundle에도 포함되지 않는다.
그렇기 때문에 데이터베이스에 쿼리를 직접 작성 할 수도 있다.

A good use case: handling form input

API Route의 좋은 사용 예는 form input을 핸들링 할 때 사용하는 것이다.
예를들어 페이지에 form을 만들고 POST request를 API Route에 보낼 수 있다. 그리고 데이터베이스에 저장하도록 코드를 작성 할 수 있다.
클라이언트 번들에 포함되지 않기 때문에 안전하게 서버 사이드 코드를 작성 할 수 있다.

export default function handler(req, res) {
  const email = req.body.email
  // Then save email to your database, etc...
}

Preview Mode

Static Generation은 페이지가 데이터를 headless CMS에서 fetch 할 때 유용하다.
하지만 headless CMS에 draft(초안)을 작성 할 때와 draft를 즉시 페이지에 preview 할 때는 이상적이지 않다.
Next.js가 이 페이지들을 build time이 아닌 request time에 렌더되고 published content가 아닌 draft content를 fetch 하길 원할 것이다.
이 특정한 경우에만 Next.js가 Static Generation을 우회하는 것이 좋다.

Next.js 는 위 문제를 해결 할 수 있는 기능인 Preview Mode 가 있다.
그리고 이것은 API Routes를 활용한다.

What is Headless CMS?

콘텐츠 저장소 역할을 하는 백엔드 전용 콘텐츠 관리 시스템이다.
프론트엔드 레이어 없이 모든 장치에서 표시할 수 있도록 API를 통해 콘텐츠에 엑세스 할 수 있다.

Dynamic API Routes

API Routes는 일반 페이지들 처럼 동적 API Route로 사용 할 수 있다.

Deploying Your Next.js App

Push to Github

github에 repository 생성 후 push

Deploy to Vercel

Vercel을 이용하면 쉽게 Next.js를 production으로 배포할 수 있다고 한다.
Vercel은 headless content, commerce, database 와 static, hybrid application 을 통합하기 위해 만들어진 serverless platform 이다.
프론트엔드 팀들이 develop, preview, ship delightful user experiences를 하기 좋게 만들어졌다고 하고 무료이다.
가입하고 github 연동을 하면 쉽게 repository 를 import 할 수 있고 deploy도 간편하게 버튼 클릭으로 할 수 있다.

with TypeScript

Next.js는 즉시 사용가능한 통합 타입스크립트 경험을 제공한다.

Create tsconfig.json

먼저 비어있는 tsconfig.json 파일을 프로젝트 root에 생성한다.
TypeScript를 다음 명령어로 설치한다.
yarn add --dev typescript @types/react @types/node
next-env.d.ts 파일이 생성된다. 이 파일은 타입스크립트 컴파일러가 Next.js types를 잘 인식 할 수 있게 해준다. 따로 건드릴 필요는 없다.
이후 타입스크립트를 Next.js app에서 사용 할 수 있다.

Next.js Specific Types

Static Generation and Server-side Rendering

getStaticProps, getStaticPaths, getServerSideProps의 타입은 GetStaticProps, GetStaticPaths, GetServerSideProps로 사용 할 수 있다.

import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

export const getStaticProps: GetStaticProps = async context => {
  // ...
}

export const getStaticPaths: GetStaticPaths = async context => {
  // ...
}

export const getServerSideProps: GetServerSideProps = async context => {
  // ...
}

API Routes

getStaticProps, getStaticPaths, getServerSideProps의 타입은 GetStaticProps, GetStaticPaths, GetServerSideProps로 사용 할 수 있다.

import { NextApiRequest, NextApiResponse } from 'next'

export default (req: NextApiRequest, res: NextApiResponse) => {
  // ...
}

Custom 'App'

pages/_app.jspages/_app.tsx로 바꾼 후 Built-in type AppProps 사용

import { AppProps } from 'next/app'

function App({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

export default App
profile
Deprecated

0개의 댓글