Skip to content

Instantly share code, notes, and snippets.

@tcrowe
Created August 23, 2019 01:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcrowe/c9a11fca78447ba78c5de2e7b9ba10d2 to your computer and use it in GitHub Desktop.
Save tcrowe/c9a11fca78447ba78c5de2e7b9ba10d2 to your computer and use it in GitHub Desktop.
polka sapper api proxy example
/*
they usually use ES Modules but i used CommonJS here
you can port it to suite your need
*/
const sirv = require("sirv");
const polka = require("polka");
const compression = require("compression");
const sapper = require("@sapper/server");
const proxy = require("express-http-proxy");
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";
const apiProxy = proxy("http://127.0.0.1:8930");
// assign server variable
const server = polka();
// ⚠️ hack to make the proxy work with polka
// express-http-proxy is expecting these methods
server.use(function(req, res, next) {
res.status = code => (res.statusCode = code);
res.set = res.setHeader.bind(res);
next();
});
// proxy to api
server.use("/api", apiProxy);
// do normal sapper server stuff
server
.use(
compression({ threshold: 0 }),
sirv("static", { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log("error", err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment