4
0

Next.jsでリバースプロキシーのかわりになるもの

Posted at

Nextjsにおけるリバースプロキシーとは

rewritesを指しています。

SPAとかで、viteとか、webpack使うと、だいたいみんな記述するやつです。
nextjsにも備わっていますが、例を出すとこんなかんじです。

http://localhost:3000/apiに来たリクエストをhttp://localhost:3001にリクエストし直す設定だと下記のようになります。

next.config.js
/** @type {import('next').NextConfig} */

const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/api/:path*",
        destination: `http://localhost:3001/:path*`,
      },
    ];
  },
};

module.exports = nextConfig;

ただ、弱点もある

いろいろ機能は揃っているものの、rewriteしたパスを考えるのは面倒になってきます。
あと、 内部的にHTTP2に対応していないようなので、gRPCへの転送は残念ながらできません。

代替え案、キャッチオールセグメント

/app/api/[...api]/route.ts

のように、[...api]でjavascriptのスプレッド構文みたいに記述すると、パスの/api/配下に来たリクエストをすべて、route.tsが受けることができます。

これだと、rewritesでやっていたことを代替えできますし、あとはパスを見たりheadersやcookiesもルートハンドラで、できるすべて叶えることができます。
gRPCのクライアントを使えば、gRPCのリクエストも出来るようになります。

/app/[...api]/route.ts

export function GET(req: NextRequest) {
  try {
    const { pathname } = new URL(req.url);
    
    if (pathname === "/api/health") {
      return Response.json({ status: 200, message: "OK" });
    }

    return Response.json({ status: 404, message: MESSAGE.NOT_FOUND });
  } catch (error) {
    return Response.json({ status: 500, error, message: MESSAGE.SERVER_ERROR });
  }
}

結果

curl http://localhost:3000/api/health
{"status":200,"message":"OK"}

現場からは以上です。

4
0
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
0