Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 38 ยท Dev Server and HMR

Proxy and History Fallback

Fix CORS and deep-link 404s in development: configure devServer.proxy for API calls, pathRewrite, WebSocket proxying, historyApiFallback for single-page apps, headers and HTTPS.

Two problems appear almost as soon as you build a real app with the dev server. First, your frontend runs on http://localhost:8080 but your API runs on http://localhost:3000, so the browser blocks the calls (CORS) and you would hard-code a different URL for production. Second, your single-page app has routes like /users/5, and refreshing the page there gives a 404 because no such file exists. The dev server has one option for each.

The proxy

A proxy forwards certain requests to another server. The browser talks only to the dev server on its own origin, so no CORS problem arises, and your code can call a relative URL like /api/users in both development and production.

JavaScript
module.exports = {
  devServer: {
    port: 8080,
    proxy: [
      {
        context: ['/api'],
        target: 'http://localhost:3000',
        changeOrigin: true,
      },
    ],
  },
};

With this, a request for http://localhost:8080/api/users is sent to http://localhost:3000/api/users, and the answer comes back through the dev server. In older versions (and still accepted) the proxy was an object keyed by path: proxy: { '/api': 'http://localhost:3000' }. The array form allows more options per rule.

flowchart LR
  B["Browser"] -->|"GET /users/5 (page)"| D["Dev server :8080"]
  B -->|"GET /api/users"| D
  D -->|"proxy"| A["API server :3000"]
  D -->|"serves bundle + index.html"| B

Only /api requests leave the dev server; everything else is served locally.

Useful proxy options:

Option Meaning
context / path key which URL prefixes to forward
target where to send them
changeOrigin rewrite the Host header to the target (needed for virtual hosts)
pathRewrite change the path before forwarding
secure set false to accept self-signed certificates on the target
ws also proxy WebSocket connections
logLevel debug to see what is proxied

pathRewrite

If the backend does not expect the /api prefix, strip it:

JavaScript
proxy: [{
  context: ['/api'],
  target: 'http://localhost:3000',
  pathRewrite: { '^/api': '' },   // /api/users -> /users
}],

The keys are regular expressions and the values replacements. You can also use router to choose the target per request, or write a bypass function to serve a local response instead of proxying.

Proxy stand-in

This demo starts two real servers on loopback ports: a fake "API" and a "dev server" that forwards /api requests to it (stripping the prefix) and serves a page for everything else.

Node.js Stand-in: a dev server that proxies /api

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In your frontend code you simply write fetch('/api/users'). In production the same relative URL works when your web server (nginx, a CDN rule) forwards /api to the backend, so no environment-specific URLs are needed.

historyApiFallback for single-page apps

A SPA router that uses the History API (/users/5 instead of /#/users/5) renders routes on the client. When the browser requests /users/5 directly (a refresh or a shared link), the server looks for a file by that name, finds none and returns 404. The fix is a fallback: for requests that look like page navigations and match no file, return index.html and let the client router take over.

JavaScript
devServer: {
  historyApiFallback: true,
}

You can customize the rules:

JavaScript
historyApiFallback: {
  disableDotRule: true,                       // allow dots in routes such as /files/v1.2
  rewrites: [
    { from: /^\/admin/, to: '/admin.html' },  // a second app shell
    { from: /./, to: '/index.html' },
  ],
},

The fallback only applies to requests that accept HTML (typed URLs, links) and are GET or HEAD; it does not catch /api/... calls made with fetch, so a missing API route still gives a real 404. And because historyApiFallback is evaluated before the proxy only for HTML requests, the two features work side by side.

Remember output.publicPath: with deep routes such as /users/5, a relative publicPath makes the browser request /users/main.js, which the fallback answers with HTML and gives "Unexpected token <". Use publicPath: '/' for SPAs (Output and Filenames).

Node.js Stand-in: history fallback decision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other server options worth knowing

  • devServer.headers: add headers such as Cross-Origin-Opener-Policy while testing features that need them.
  • devServer.server: 'https' (older: https: true): serve over TLS with a self-signed or locally trusted certificate, needed to test service workers on non-localhost hosts and some browser APIs.
  • devServer.setupMiddlewares: add your own Express-style middleware, for example mock endpoints before the backend exists.
  • devServer.allowedHosts: required when you open the dev server through a tunnel or a custom hostname.
JavaScript
setupMiddlewares: (middlewares, devServer) => {
  devServer.app.get('/mock/health', (req, res) => res.json({ ok: true }));
  return middlewares;
},

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does proxying /api through the dev server avoid CORS errors?

    Same-origin requests are not subject to CORS; the dev server makes the cross-origin call itself.
  2. 2. What does pathRewrite: { '^/api': '' } do?

    It rewrites the path with a regular expression, here stripping the prefix.
  3. 3. What problem does historyApiFallback solve?

    The server returns index.html for navigation requests that match no file, so the client router can render the route.
  4. 4. A deep route loads, but main.js request returns HTML and fails with "Unexpected token <". What is a likely cause?

    With a relative publicPath the browser requests assets relative to the route, and the fallback answers with HTML.

Summary

  • devServer.proxy forwards selected paths (such as /api) to another server, avoiding CORS and environment-specific URLs.
  • Use changeOrigin, pathRewrite, secure and ws to fit the backend.
  • historyApiFallback serves index.html for unknown navigation requests so client-side routes survive a refresh.
  • Set publicPath: '/' for SPAs with deep routes.
  • Extra options: headers, server: 'https', setupMiddlewares and allowedHosts.

Next: Code Splitting