DEV Community

Lea Rosema (she/her) for Studio M - Song

Posted on • Edited on

Proxy your Backend API to the Parcel Development Server

When working with Parcel, I missed the option to proxy the backend API to the frontend development server.

Parcel runs on localhost:1234 and my API backend server runs on localhost:1337. I would like to have both the API server as well as the frontend server on the same site, this way you don't have to deal with CORS and you can use secure settings for cookies, like SameSite=Strict.

In a production environment, you would setup some kind of reverse proxy for that. This could be achieved with NGINX, for example.

In your development environment, you will still like to have the features of Parcel, like Hot Module Reloading.

I've built a node.js express script using the parcel-bundler as an express middleware, together with http-proxy-middleware:

const proxy = require('http-proxy-middleware').createProxyMiddleware;
const Bundler = require('parcel-bundler');
const express = require('express');

const bundler = new Bundler('src/index.html');
const app = express();

app.use(
  '/api',
  proxy({
    target: process.env.API_SERVER || 'http://localhost:1337/'
  })
);

app.use(bundler.middleware());

app.listen(Number(process.env.PORT || 1234));
Enter fullscreen mode Exit fullscreen mode

In package.json, I replaced the start script that used the parcel script with node server.

As a demo project, I have created a clone of https://yesno.wtf
It provides a node.js express backend and a react application.

https://github.com/terabaud/yesno-clone

Do you have questions or feedback? Feel free to leave a comment.

Top comments (0)