LoginSignup
4
4

More than 3 years have passed since last update.

Next.js: Vercelでカスタムサーバーが使えない…と気づいた時の対処

Posted at

Vercelでカスタムサーバーは使えない

server.js が動いていない?

先日 Vercel にデプロイした Next.js のアプリの挙動確認をしていたのですが、どうやら上手く動いてない箇所がありました。

問題となっていたのは、Express.js で実装していたカスタムサーバーの server.js

これが全く動いていませんでした。

「使えません」 by 公式ドキュメント

原因調査しましたが、普通に公式ドキュメントの「カスタムサーバー」のところに書いていました。

A custom server can not be deployed on Vercel, the platform Next.js was made for.

そう、「カスタムサーバーはVercelにはデプロイできません」と…。

公式ドキュメントはしっかり読みましょう!

後から気づいた時の対処

デプロイしてからこの事実に気がついた場合、次の2つの対処法が考えられます。

1. API Routes で代替する

元のカスタムサーバーで、特に複雑なことをしていなければ、API Routes で代替するのが1番でしょう。

使い方

pages/api 配下に任意のファイルを作り、handler(req, res) を書くだけでAPIのエンドポイント(サーバーサイドの処理)が作れます。

例えば、/api/example というエンドポイントを作りたい場合、次のようになります。

pages/api/example.js
export default function handler(req, res) {
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ name: 'Hello World from example.js' }))
}

TypeScript の場合

TypeScript で書く場合は、次のようになります。

pages/api/example.ts
import { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ name: 'Hello World from example.ts' }))
}

環境変数も普通に使える

環境変数も NEXT_PUBLIC_ なしで普通に使えます。

Environment Variables 公式ドキュメント より

This loads process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically allowing you to use them in Next.js data fetching methods and API routes.

2. 別の PaaS にデプロイする

いや、カスタムサーバーが必要なんだ!

という場合は、別の Platform as a Service (PaaS) 等にデプロイするしかありません。

Heroku にデプロイするなら次のGitHubページが参考になりそうです。

GitHub: mars/heroku-nextjs-custom-server-express

まとめ

  • Vercelでカスタムサーバーは使えない
  • ほとんどの場合、API Routesで代替できる
  • カスタムサーバーが必要な場合は、別のPaaSにデプロイする

References

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4