LoginSignup
2
1

More than 3 years have passed since last update.

next.js で /api 以外をAPI endpointとして公開する方法

Last updated at Posted at 2021-02-09

概要

next.js にはVercelのserverless functions を土台としたAPI routes機能があり、APIを公開できる
このエンドポイントは /api/* となっている
これを違うパスからアクセス可能にしたい需要があった
しかし規約が強く、基本的には /api からのエンドポイント変更は無理そうだった
そのときに思いついてうまくいった方法

方法

Rewrites を設定する

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/hoge/:hoge*',
        destination: '/api/:hoge*',
      },
    ];
  },
};

これで /hoge/*/api/* と同等になる

懸念

/api は消えない(隠せない)ので、エンドポイントを1つにしたいという需要があった場合は満たせない

他に方法があるか

https://vercel.com/docs/configuration#project/builds

https://vercel.com/docs/configuration#project/functions
には直接的に書いておらず、そもそもbuild設定変更は強く非推奨となっているので、自分が読み解く限りでは基本的に無理そう

[追記]
vercel自体が /api を serverless function endpointにしているので、もしnext.js (@vercel/next) を使わずvercelだけ使っている場合はvercel.jsonのroutes設定 を使えばできるかもしれない
手元のnext.js & vercelで試した結果、 以下のメッセージにあるように無効化されたようで、望みの挙動は得られなかった

WARNING: your application is being opted out of @vercel/next's optimized lambdas mode due to legacy routes in vercel.json. http://err.sh/vercel/vercel/next-legacy-routes-optimized-lambdas

next.jsを使っていたらrewrites/redirectsを使うべきらしい

2
1
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
2
1