TL;DR
このページでは、一般的な 型定義ではなく、Next.js(Pages Router 版) 専用の型定義の具体的な使い方について解説しますね。Pages Router 版で開発をされている方対象です。
開発環境 | バージョン |
---|---|
Next.js(Pages Router) | 13.4.4 |
TypeScript | 5.0.4 |
Emotion | 11.11.0 |
React | 18.2.0 |
Next.js の「型定義」
型定義は TypeScript の重要な機能の一つで、変数や関数の引数、戻り値の型を明示することでコードの安全性を高め、開発者が意図しないデータの操作を防ぎます。また、型を明示することで、エディタの自動補完機能が向上し、開発効率が向上します。
Next.js では様々な型定義が提供されており、それぞれが Next.js の異なる機能に対応しています。これらの型定義を適切に使うことで、Next.js の機能をより効果的に活用することができます。
例えば、Next.js のページコンポーネントの型定義 NextPage
は以下のように使用します。
import type { NextPage } from 'next'
type Props = {
message: string
}
const HomePage: NextPage<Props> = ({ message }) => {
return <div>{message}</div>
}
export default HomePage
ここで、NextPage
は Next.js のページコンポーネントを表す型で、Props の型を引数に取ることができます。この HomePage
コンポーネントは message
という名前の prop を受け取り、その prop を表示します。
NextPage
NextPage
は Next.js のページコンポーネントの型定義です。Props として受け取るデータの型を指定することができます。
import type { NextPage } from 'next'
type Props = {
title: string
}
const HomePage: NextPage<Props> = ({ title }) => {
return <h1>{title}</h1>
}
export default HomePage
このコードでは、HomePage
コンポーネントが title
という名前の prop を受け取り、その prop を見出しとして表示します。
GetStaticPaths
GetStaticPaths
は静的生成のためのパスを定義する関数の型です。静的生成が必要なパスのリストを返します。
import type { GetStaticPaths } from 'next'
export const getStaticPaths: GetStaticPaths = async () => {
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false,
}
}
このコードでは、getStaticPaths
関数が 1
と 2
の id を持つパスのリストを返します。返されたパスは静的生成の対象となります。
GetStaticProps
GetStaticProps
は静的生成のための props を生成する関数の型です。生成したいページごとに必要な props を返します。
import type { GetStaticProps } from 'next'
type Props = {
data: string
}
export const getStaticProps: GetStaticProps<Props> = async () => {
const data = 'Hello, Next.js!'
return { props: { data } }
}
このコードでは、getStaticProps
関数が data
を含む props を返します。返された props は静的生成されるページのコンポーネントに渡されます。
GetStaticPropsContext
GetStaticPropsContext
は Next.js の型で、静的生成のためのデータ取得関数getStaticProps
に渡されるパラメータを表現します。この型は、ページのパスパラメータ、プレビューモードの情報、ロケールの情報などを含むオブジェクトを定義します。
import { GetStaticProps, GetStaticPropsContext } from 'next'
export const getStaticProps: GetStaticProps = async (context: GetStaticPropsContext) => {
const id = context.params?.id
// データ取得処理...
return {
props: {
// ページコンポーネントに渡すプロパティ...
},
}
}
このコードは、getStaticProps
関数を定義しています。この関数は、ページのパスパラメータからid
を取得し、それを使用してデータを取得します。取得したデータは、ページコンポーネントのプロパティとして渡されます。
GetServerSideProps
GetServerSideProps
はサーバサイドレンダリングのための props を生成する関数の型です。生成するページごとに必要な props を返します。
import type { GetServerSideProps } from 'next'
type Props = {
data: string
}
export const getServerSideProps: GetServerSideProps<Props> = async () => {
const data = 'Hello, server side rendering!'
return { props: { data } }
}
このコードでは、getServerSideProps
関数が data
を含む props を返します。返された props はサーバサイドレンダリングされるページのコンポーネントに渡されます。
NextRequest
NextRequest
は Next.js の Edge Runtime で使用される型で、クライアントからの HTTP リクエストを表現します。この型は、リクエストの URL、メソッド、ヘッダー、クッキーなどの情報を含むオブジェクトを定義します。
import type { NextRequest } from 'next/server'
export const config = {
runtime: 'edge',
}
export default async function handler(req: NextRequest) {
const { searchParams } = new URL(req.url)
const email = searchParams.get('email')
return new Response(email)
}
このコードは、クライアントからのリクエストの URL から email パラメータを取得し、その値をレスポンスとして返す Edge API ルートを定義しています。
NextResponse
NextResponse
は Next.js のサーバーコンポーネントで、HTTP レスポンスを表現するためのクラスです。このクラスは、レスポンスのステータスコード、ヘッダー、ボディなどの情報を含むオブジェクトを定義します。
デプロイ時に、Edge 関数を特定のリージョンに制限したい場合があります。これにより、データソースの近くに配置することでレスポンス時間を短縮することが可能になります。以下のように設定することでこれを実現できます。
注:この設定は Next.js のバージョン 12.3.2 以降で利用可能です。
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export const config = {
regions: ['sfo1', 'iad1'], // デフォルトは 'all'
}
export default async function handler(req: NextRequest) {
const myData = await getNearbyData()
return NextResponse.json(myData)
}
このコードでは、config
オブジェクトをエクスポートして、Edge 関数のデプロイ先のリージョンを指定しています。ここでは、sfo1
(サンフランシスコ)とiad1
(ノーザンバージニア)の 2 つのリージョンを指定しています。デフォルトでは、すべてのリージョン(all
)が対象となります。
NextApiRequest
NextApiRequest
は API ルートのリクエストオブジェクトの型です。これは、Node.js の HTTP IncomingMessage オブジェクトを拡張したものになります。クエリパラメーターやリクエストボディ、ヘッダーなどを取得する際に使用します。
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
console.log(req.body) // access request body
console.log(req.query) // access query parameters
res.status(200).json({ message: 'Hello Next.js!' })
}
NextApiResponse
NextApiResponse
は API ルートのレスポンスオブジェクトの型です。これは、Node.js の HTTP ServerResponse オブジェクトを拡張したもので、レスポンスを送る際に使用します。
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: 'Hello Next.js!' }) // sending response
}
InferGetStaticPropsType
InferGetStaticPropsType
はgetStaticProps
関数の戻り値型を推論するためのユーティリティ型です。これを使用すると、props の型を明示的に記述せずに済みます。
import type { InferGetStaticPropsType } from 'next'
type Post = {
author: string
content: string
}
export const getStaticProps = async () => {
const posts: Post[] = await getDataFromCMS() // fetch posts
return { props: { posts } }
}
const Blog = ({ posts }: InferGetStaticPropsType<typeof getStaticProps>) => {
/* render posts */
}
export default Blog
InferGetServerSidePropsType
InferGetServerSidePropsType
はgetServerSideProps
関数の戻り値型を推論するためのユーティリティ型です。InferGetStaticPropsType
と同様に、props の型を明示的に記述せずに済みます。
import type { InferGetServerSidePropsType } from 'next'
type User = {
name: string
email: string
}
export const getServerSideProps = async () => {
const users: User[] = await getUsersFromDB() // fetch users
return { props: { users } }
}
const UsersPage = ({ users }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
/* render users */
}
export default UsersPage
NextApiHandler
NextApiHandler
は API ルートのハンドラ関数の型です。リクエストとレスポンスの型を引数に取ります。
import type { NextApiHandler } from 'next'
const handler: NextApiHandler = (req, res) => {
res.status(200).json({ message: 'Hello Next.js!' })
}
export default handler
NextComponentType
NextComponentType
は Next.js のページコンポーネントの型を表します。この型は、NextPageContext
、AppInitialProps
、そして任意のページが受け取る props の型を引数に取ります。
import type { NextComponentType } from 'next'
import type { NextPageContext } from 'next'
import type { AppInitialProps } from 'next/app'
type PageProps = {
custom: string
}
const Page: NextComponentType<NextPageContext, AppInitialProps, PageProps> = ({ custom }) => {
return <div>{custom}</div>
}
export default Page
AppProps
AppProps
は Next.js のカスタム _app
コンポーネントの props の型です。これはページの初期 props と、現在のページコンポーネントとその URL に関する情報を提供します。
import type { AppProps } from 'next/app'
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
export default MyApp
AppContext
AppContext
はカスタム _app
コンポーネントのコンテキストオブジェクトの型です。これは getInitialProps
関数内で利用可能で、現在のページの情報などを提供します。
import type { AppContext } from 'next/app'
MyApp.getInitialProps = async (appContext: AppContext) => {
const appProps = await App.getInitialProps(appContext)
return { ...appProps }
}
AppInitialProps
AppInitialProps
は _app
コンポーネントの初期 props の型です。
import type { AppInitialProps } from 'next/app'
MyApp.getInitialProps = async (appContext): Promise<AppInitialProps> => {
return { pageProps: {} }
}
これらの型定義を理解し、適切に使用することで、Next.js の開発をより安全かつ効率的に行うことができます。