Dynamic data in your Gatsby Serverless Functions

How do you get data into a serverless function?

There are three common approaches:

1. Using URL Queries

Demo

Documentation

Serverless Function Code

// File: /api/time-travel-query
// Usage: /api/time-travel-query?city=oslo&year=1624
export default function handler(req, res) {
  const { city, year } = req.query;
  res.send(`You time-travelled to ${city}, in year ${year}`);
}

2. Using Param Routes

Demo

Documentation

Serverless Function Code

// File: /api/time-travel-params/[city]/[year].js
// Usage: /api/time-travel-params/oslo/1624
export default function handler(req, res) {
  const { city, year } = req.params;
  res.send(`You time-travelled to ${city}, in year ${year}`);
}

3. Using Http Request Body

Demo



Documentation

Serverless Function Code

// File: /api/time-travel-body.js
// Usage: {city: "Oslo", year: "2026"} added to request body
export default function handler(req, res) {
  const { city, year } = req.body;
  res.send(`You time-travelled to ${city}, in year ${year}`);
}

Check out the full demo code on GitHub or take it for a spin using CodeSandbox.

 
All the best,
Queen Raae

PS: Yesterday was May 17th, a special day in Norway. Check out the reason and the fam in our finest on Twitter.

Interested in more daily treasures like this one?
Sent directly to your inbox?