Skip to content

Commit

Permalink
Proxy CANISTER.localhost (#2102)
Browse files Browse the repository at this point in the history
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:<vite port>` request.
  • Loading branch information
nmattia authored Dec 5, 2023
1 parent 3fe159a commit 01cef4a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
6 changes: 0 additions & 6 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
? [
{
Expand Down
13 changes: 12 additions & 1 deletion vite.plugins.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -148,6 +149,16 @@ export const replicaForwardPlugin = ({
return forwardToReplica({ canisterId: subdomain });
}

// Try to read the canister ID of a potential canister called <subdomain>
// 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();
});
},
Expand Down

0 comments on commit 01cef4a

Please sign in to comment.