0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nestjsでproxyを利用する

Posted at

nestjsでproxyを利用する

背景

docker containerを利用して、nestjsのportでviteのstatic renderingを利用しようとした。
HMRをnestjsのview層から配信するように実装しようとすると、proxyを利用した方が楽そうだったので、nestjs側でviteのrun server向けにproxyを組むことを試してみた。

0. 前提と依存関係

package version link
nestjs 10.4.9 docs
http-proxy-middleware 3.0.3 repo

1. http-proxyを利用する

開発環で利用することを想定して、最低限の対応を実施

proxy.ts
import { createProxyMiddleware } from 'http-proxy-middleware';

const PROXY_TARGET = "http://ui_container:4200"

const simpleRequestLogger = (proxyServer) => {
  proxyServer.on('proxyReq', (proxyReq, req) => {
    console.log(`[HPM] [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
  });
  proxyServer.on('proxyRes', (proxyReq, req, res) => {
    console.log(`[HPM r] ${res} [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
  });
  proxyServer.on('error', (err, req) => {
    console.log(`[HPM e] ${err} [${req.method}] ${req.url}`); // outputs: [HPM] GET /users
  });
};

export const proxy = createProxyMiddleware({
  target: PROXY_TARGET,
  changeOrigin: true,
  ws: true,
  plugins: [simpleRequestLogger],
});

proxyをcontrollerで利用する。
(middlewareというよりは、実態なのでcontrollerに記載した)。

sample.controller.ts
import { Controller, Get, Next, Req, Res } from '@nestjs/common';
import { proxy } from '../libs/proxy';

@Controller('@vite')
export class ViteController {
  @Get('client')
  async proxyViteClient(@Req() req, @Res() res, @Next() next) {
    try {
      return await proxy(req, res, next);
    } catch (e: unknown) {
      console.log(e);
    }
  }
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?