Decoupling front end and back end

Rodrigo Pombo
Hexacta Engineering
3 min readApr 19, 2017

You are starting a new project, a web application. You are thinking on a REST API for the back end and a single page application for the front end. You choose, let’s say, Node and Express for the API and React for the SPA. Cool, now you create an empty folder and start boilerplating your back end, yada yada yada, you end up with an Express middleware to serve your SPA static files from a “public” folder.

Stop. Why is your API now serving static files? Remember your last job interview, when the interviewer asked about separation of concerns? Well, this is a good example of togetherness of concerns. I could now start writing about the problems that this approach brings but I will assume you are already convinced and start talking about an alternative approach.

We want a project structure that:

  • Lets you work on one end without depending on the other
  • Allows you to run both ends at the same time
  • Lets you build and deploy both ends together or separated
  • Makes it easy to use different tools on each end

Let‘s change the approach. We’ll use npm for dependencies and build scripts, Express for the back end API, and Create React App boilerplate for the front end (the idea should remain the same for other tools and frameworks).

Again, we start with an empty “my-app” folder. Inside we create two folders, one called “api” and the other “web”. Now we open the api folder and forget everything we may know about SPAs, React, and browsers, we just focus on the back end.

project structure

We start by installing some dependencies and some tools… fast forward 20 minutes and we have a “src” folder where we keep all the back end source files, we also have a scripts for transpiling source code, a script for running the API in development mode while watching the files for changes, and more (you can check the full api folder in github).

Then we move to the front end, we go to the web folder and let create-react-app create all the code for us. In the package.json we add the proxy property so we don’t have to enable CORS: “proxy”: “http://localhost:8080/”.

We now have two different and uncoupled folders, one for the front end and one for the back end. But, we still want to do some things that include both folders at the same time. For example, we want to run “npm install” just once and not one for each folder, the same with “npm start”.

So we create a package.json in the root folder and call the scripts from both subfolders:

That’s all, you can see the full repository on github, including how to build and deploy it with nginx and docker. There is another blog post showing how to do automatic deploys with a similar project structure to Google Container Engine:

Thanks for reading.

I build things at Hexacta.

Have an idea or project we can help with? Write us.

--

--