React
를 SSR
가능하게 해주는 프레임워크 (SEO
가능)Next.js 는 React 기반 Framework
폴더 및 파일 기반 Routing 지원하고, Server Side Rendering을 지원
즉, SEO 적용이 수월
컴파일과 번들링이 자동 (webpack 과 babel)
자동 리프레쉬 기능으로 수정하면 화면에 바로 반영
서버사이드 렌더링 지원
정적 파일을 지원
npx create-next-app@latest [폴더명]
TypeScript
npx create-next-app@latest --ts [폴더명]
yarn create next-app [폴더명]
TypeScript
yarn create next-app --typescript [폴더명]
// import App from 'next/app'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
export default MyApp
componentDidCatch
를 이용해 커스텀 에러 핸들링 가능_app
은 서버로 요청이 들어왔을 때 가장 먼저 실행되는 컴포넌트로, 페이지에 적용할 공통 레이아웃의 역할_app
은 로직, 전역 스타일 등 컴포넌트에 공통 데이터를 다룸import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
_document
는 _app
다음에 실행되며, 공통적으로 활용할 <head>
(Ex. 메타 태그)나 <body>
태그 안에 들어갈 내용들을 커스텀할때 활용_document
는 공통적으로 적용할 HTML 마크업을 중심다룸_document
를 작성할 때는 Document 클래스를 상속받는 클래스 컴포넌트로 작성해야만 하며, 렌더 함수는 꼭 <Html>
, <Head>
, <Main>
, <NextScript>
요소를 리턴
_document
에서 사용하는 <Head>
태그는 next/head가 아닌 next/document 모듈에서 불러와야 하는데, _document
의 <Head>
태그에는 모든 문서에 공통적으로 적용될 내용(Ex. charset, 뷰포트 메타태그 등)이 들어가야함
- Static Generation 정적 생성
- Server Side Rendering (SSR, Dynamic Rendering)
차이점은 언제 html 파일을 생성하는가?
getStaticProps
/ getStaticPaths
export async function getStaticProps(context) {
return {
// will be passed to the page component as props
props: {},
}
}
export async function getStaticPaths() {
return {
paths: [
// See the "paths" section below
{ params: { ... } }
],
// See the "fallback" section below
fallback: true, false, or 'blocking'
};
}
getServerSideProps
export async function getServerSideProps(context) {
return {
// will be passed to the page component as props
props: {},
}
}
function Error({ statusCode }) {
return (
<p>
{statusCode
? `An error ${statusCode} occurred on server`
: 'An error occurred on client'}
</p>
)
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404
return { statusCode }
}
export default Error
// node.js
process.env.변수명
// next.js
process.env.NEXT_PUBLIC_변수명
export default function handler(req, res) {
const { pid } = req.query
res.end(`Post: ${pid}`)
}