Using `polymer serve` with local API server

655 views Asked by At

I want to use polymer serve to serve my LitElement app during development without waiting for polymer build to finish after every change. However, the app uses relative URLs for API access, like GET /api/api_method, and AFAIK I can't make polymer serve and my server work on the same port (e.g. localhost:8080).

Currently I run polymer build and then run my local Python server, which serves the Polymer files as static.

The ideal scenario would be:

$ run_my_server.sh --port=8081
$ polymer serve --api_server="localhost:8081"

Then for routes that are found in the polymer build directory they would be served, otherwise the request would be routed to localhost:8081.

Are there any other ways to setup the local dev process without rebuilding the whole app after every change?

1

There are 1 answers

4
daKmoR On BEST ANSWER

Usually, you would do this with a proxy middleware - however, polymer server does not allow to add your own middleware.

So you have 2 options:

  1. basically what you are doing e.g. wrapping polymer serve and forward requests
  2. use a different server that supports a proxy middleware

As an example the es-dev-server.

install

npm i -D es-dev-server koa-proxies

create a es-dev-server.config.js

const proxy = require('koa-proxies');

module.exports = {
  port: 9000,
  middlewares: [
    proxy('/api', {
      target: 'http://localhost:8081',
    })
  ],
};

start with

es-dev-server --node-resolve

Now if you hit http://localhost:9000 you will be served by the es-dev-server. However, if you hit http://localhost:9000/api then it will actually serve from your api server.

Doing this allows to simply use fetch when requesting from the api as all get served from the same domain + port.

You can find more details for here: https://open-wc.org/developing/es-dev-server.html#custom-middlewares-proxy

PS: I am a co-maintainer