From 01cef4a39b334253652ab5d3dcc297c33d9de031 Mon Sep 17 00:00:00 2001 From: Nicolas Mattia Date: Tue, 5 Dec 2023 10:08:22 +0100 Subject: [PATCH] Proxy CANISTER.localhost (#2102) This changes the local setup -- in particular, the `replicaForwardPlugin` -- to allow redirecting to canister by names. Until now, `NAME.localhost` had to be added manually as a host, alongside with a canister name. With these changes, the replica forward plugin will try find a local canister `foo` to proxy to for any `foo.localhost:` request. --- vite.config.ts | 6 ------ vite.plugins.ts | 13 ++++++++++++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/vite.config.ts b/vite.config.ts index bcd0b38af6..cc9986a94c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -74,12 +74,6 @@ export default defineConfig(({ mode }: UserConfig): UserConfig => { hosts: ["nice-name.com"], canisterName: "test_app", }, - { - /* nice for deploying locally without having - * to look up & type the canister ID */ - hosts: ["issuer.localhost:5173"], - canisterName: "issuer", - }, ...(process.env.NO_HOT_RELOAD === "1" ? [ { diff --git a/vite.plugins.ts b/vite.plugins.ts index 59ab13172d..5edad948e0 100644 --- a/vite.plugins.ts +++ b/vite.plugins.ts @@ -1,4 +1,5 @@ import { isNullish } from "@dfinity/utils"; +import { execSync } from "child_process"; import { minify } from "html-minifier-terser"; import httpProxy from "http-proxy"; import { extname } from "path"; @@ -99,7 +100,7 @@ export const replicaForwardPlugin = ({ // forward to the specified canister (served by the replica) const forwardToReplica = ({ canisterId }: { canisterId: string }) => { console.log( - `forwarding ${req.method} https://${req.headers.host}${req.url} to canister ${canisterId}` + `forwarding ${req.method} https://${req.headers.host}${req.url} to canister ${canisterId} ${replicaOrigin}` ); req.headers["host"] = `${canisterId}.localhost`; proxy.web(req, res, { @@ -148,6 +149,16 @@ export const replicaForwardPlugin = ({ return forwardToReplica({ canisterId: subdomain }); } + // Try to read the canister ID of a potential canister called + // and if found forward to that + try { + const canisterId = execSync(`dfx canister id ${subdomain}`) + .toString() + .trim(); + console.log("Forwarding to", canisterId); + return forwardToReplica({ canisterId }); + } catch {} + return next(); }); },