lwsjs / local-web-server

A lean, modular web server for rapid full-stack development.
MIT License
1.2k stars 85 forks source link

rewrite try local then proxy if it doesn't exist #145

Closed JoA-MoS closed 4 years ago

JoA-MoS commented 4 years ago

Is there a way to configure lws to try the locally first before rewriting?

75lb commented 4 years ago

No, it's not a built-in feature but would you want to being waiting for the local request to timeout before trying the remote server?

If it was me, I'd have a config file looking something like this.

const remoteAPI = process.env.REMOTE_API || 'localhost'

module.exports = {
  rewrite: [
    {
      from: '/resources/(.*)',
      to: `http://${remoteAPI}/resources/$1`
    }
  ]
}

You can run the server as usual like this.

$ ws

If for some reason, you want to switch to the remote API, run it like this.

$ REMOTE_API=dev.api.example.com ws
JoA-MoS commented 4 years ago

I have a small project that is hosted referencing a lot of other static file already created, because of the way our dated CMS system is set up static content JS/CSS/Images need to be hosted under the static directory. For local development I use local web server and I proxy most of the requests to the actual dev server so I don't have to pull all the content I can't actually make changes to.

I want all requests to /static/ except /static/myproject/ to be rewritten. I tried writing a negative look ahead but that doesn't seem to be supported

module.exports = {
  directory: 'src',
  port: 5000,
  rewrite: [
    {
      from: '/static/(.*)',
      to: 'https://my-dev.server.com/static/$1',
    },
  ],
  logFormat: 'dev',
};

This is a pretty common practice https://angular.io/guide/deployment#fallback-configuration-examples (my project is not an angular project this was just a good example)

75lb commented 4 years ago

The from syntax is a path-to-regexp route expression (used also by the Express internals). So, if you want to use a traditional RegExp technique like negative look ahead, maybe look into using a custom matching parameter.

If that doesn't work or is just too complex, solve it using multiple rewrite rules e.g.

module.exports = {
  ...
  rewrite: [
    {
      from: '/static/css/(.*)',
      to: 'https://my-dev.server.com/static/css/$1',
    },
    {
      from: '/static/myproject/css/(.*)',
      to: 'https://localhost/static/css/$1',
    },
    etc,
    etc
  ],
  ...
};
JoA-MoS commented 4 years ago

Thanks! that works