Setup cPanel Node.js application to proxy to frontend
| Node.js, website
So imagine you've got the following:
- Access to cPanel for a shared host with your own domain name
- A frontend written using Next.js, Gatsby.js or something else that requires you to use 'npm start xyz' to run it
- And a desire to have a custom backend to handle fun things like Sockets, authentication, and DB stuff
A simple solution:
- Push the production version of your frontend to Next.js or Gatsby.js using their suggested approach
- Host the backend on your server using cPanel and a custom server.js "application".
- Add some code to server.js to proxy to your frontend URL
I say this is a simple solution, because as you can see below the are very few lines of code required to get this to work. And the beuty of it is that you achieve a nice separation of frontend and backend, and yet present a unified experience to your users.
Let's have a look at that code. Updating server.js to proxy to APP_URL.
var app = require('express')();
const { createProxyMiddleware } = require('http-proxy-middleware');
...
app.use('/', createProxyMiddleware({
target: APP_URL,
changeOrigin: true,
}));
That's it!