How to run Node express backend for Gatsby app

Suraj Shrestha
Siris Technology
Published in
1 min readJul 28, 2019

--

Static-site-generator tools like Gatsby are awesome tools for creating

  • Sites that has mostly static components
  • Sites that don’t have heavy backend and few api calls to external api providers

It is perfect for creating a company portfolio website like we did or developer portfolio website.

However, there will be cases where we need some backend. For example, saving feedback message when user submits through contact form.

And, it is not feasible or economical to create/deploy/host a complete new app for such a tiny service.

So, what can we do?

Gatsby is not great at proxying api calls in production environment. This link only works in dev environment.

Couple of Options

  • gatsby exports all html into /public folder. You can simple serve static files through your express app.

app.use(express.static(`${__dirname}/public`)) e.g. link

  • Another easy solution is to run gatsby serve and node express in the same port. You can make express run in background daemon using libraries likepm2 .

web: pm2 start ecosystem.config.js — env production && gatsby serve -p $PORT -H 0.0.0.0

  • Netlify function is a great example and perfect for this type of scenario (static website with some api support through function). Netlify free tier is also adequate for most of the small scale websites, however, the price rises sharply after that.

--

--