Published on

Next.jsでjsonを返す静的ページの作り方

Authors
  • avatar
    Name
    ssu
    Twitter

あるとき機能開発しているときに、 Next.jsで静的なページでjsonを返して、apiのように扱いたい時がありました。

もちろんfunctionなどを使ってapiを提供するというのはあったのですが、 なかなか静的ページ(SSG)でapiのようにjsonを返すというのがありませんでした。

そこで、今回はNext.js静的ページでjsonを返すページの作り方を紹介します。

Next.jsでapiのようにjsonを返すページの作り方

すごく簡単にできます。

  1. まずはpageのディレクトリにページを作ります。
  2. 次に以下のようにgetServerSidePropsを設定するだけです
const Home = () => {} export async function getServerSideProps({req, res, context, query}) { const data = { id: 1232, name: 'sato'} res.setHeader('Content-Type', 'application/json') res.write(JSON.stringify(data)) res.end() return { props: {}} //これがなくても動くのですが、errorが出るためこれを追加しています。 } export default Home

クエリーパラメータに応じてJSONを返すやり方

さらにqueryに応じて、送るデータを変化させることや、リクエストがjsonの時にだけjsonデータを返すことも可能です。

const Home = () => { } export async function getServerSideProps({req, res, context, query}) { var data = [{ id: 1232, name: 'sato'}, { id: 1235, name: 'yamada'}] if (req.headers.accept === "application/json") { res.setHeader('Content-Type', 'application/json') if (query.user_id) { data = data.find(x => x.id.toString() == query.user_id) // queryに応じた処理 } res.write(JSON.stringify(data)) res.end() } return { props: {}} } export default Home

参考: Different Content-Types on the same route with Serverless Next JS

参考: How to set custom HTTP response headers in Next.js without using a custom server?