Build simple backends with Gatsby Serverless Functions

Until recently adding a little backend to your Gatsby site meant 2 options:

  1. Climbing the AWS learning curve
  2. Rewrite with NextJS

With version 3.7 Gatsby gained the /api directory. Pop a JavaScript or TypeScript file in src/api, export a handler, and you've got a serverless function.

// src/api/hello.js
module.exports = function handler(req, res) {
  return res.status(200).json({ hello: req.query.name })
}

You can call that as an API request from your site. Great for 3rd party integrations with secret tokens, user reactions, authentication, and anything else you can't do in the browser.

I joined Queen Raae on a bonus episode of her Gatsby Summer Functions webinar series to explore how all this works.

Architecting your Gatsby Serverless Functions

We started with my crappy implementation of a function that takes a form submission and:

We refactored this serverless function so it's faster and more reliable. While refactoring we talked about:

And I drew a sketch, live 🤘

Enjoy the webinar, hit reply if you have questions.

And if you'd like a deeper introduction to serverless, the Serverless Handbook is full of sketches like that.

Cheers,
~Swizec

PS: yes, there's options between AWS and NextJS like Firebase or Netlify cloud functions. And even tougher climbs like hosting your own servers. Adding those made the intro too long ✌️