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?

Vite開発サーバーでAPIフェッチできるようにserver.proxyを使う

0
Posted at

やりたいこと

本番環境で同一オリジンのAPIをフェッチしながら動くフロントエンドを
npm run devの開発者サーバーで動かしながら開発したい

解決手段

Viteのserver.proxyでリバースプロキシするのが簡単です

課題

Reactなどでフロントエンド開発を行う場合、npm run devで開発するとコードを書き換えて保存したらブラウザ側も更新されていてコーディングがはかどりますが、バックエンドAPIからフェッチして動かそうとする場合はCORSが問題になります

例えば本番環境においてフロントエンドをexample.com、APIをexample.com/apiに配置するとします。リバースプロキシで1つのオリジンに集めてやるという想定で、同一オリジンでデプロイすればCORS不許可にできますので攻撃面を減らすことができます

一方、npm run devで起動した開発サーバーはlocalhostで起動しますので、API側でlocalhostをCORS許可していないとフェッチできません。バックエンドも開発中ならCORSを全部外したりlocalhostをCORS許可したりで対応できますが、完成して運用中だとそうはいきませんし、CORSの設定を外したり付けたりするのも面倒かつリスキーです

解決方法

Viteのserver.proxyを使えば開発サーバー側でAPIのみリバースプロキシしてやる事ができます

server.proxyに/apiをexample.com/apiにプロキシするように設定しておくと、ブラウザから見るとlocalhost:5173でフロントエンドが動作し、JavaScriptからlocalhost:5173/apiのAPIをフェッチしているだけなので同一オリジンとしてブロックしないのですが、開発サーバーがexample.com/apiにルーティングしてくれるので、CORSを回避してAPIフェッチが可能になります

要は、開発サーバーが動かしているオリジンに限り、開発者自身のブラウザのCORSを回避してやるということですね。server.proxyは開発サーバーにリバースプロキシさせる指示ですので、本番環境の挙動には関係ありませんから、リバースプロキシしている本番環境を再現する為の機能といえると思います

使い方

server.proxy要素内にPATHとURLを書くだけです

パスが同一の場合

/api/hogeでexample.com/api/hogeを呼ぶような
パスが同一である場合は以下のように書きます

vite.config.ts
import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
  server: {
    proxy: {
      "/api": {
        target: "http://example.com",
        changeOrigin: true,
      },
    },
  },
});

パスが異なる場合

/api/hogeでexample.com/hogeを呼ぶような
パスが異なる場合合は以下のようにrewriteで指定します

vite.config.ts
import { reactRouter } from "@react-router/dev/vite";
import tailwindcss from "@tailwindcss/vite";
import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'https://example.com', // オリジンのみ
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''), // /api を削除
      },
    },
  },
});
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?