Leveraging Netlify’s serverless functions

Visakh Vijayan
2 min readMar 19, 2024

Quote Quest is our hobby project which we keep working on now and then when we are bored. Today we decided we wanted to shift from Firebase’s serverless functions to Netlify. The reason is simple. We didn’t want to upgrade our basic plan on Firebase just to execute a small function.

Serverless Functions are functions that you can easily deploy on platforms like Firebase and Netlify. They provide you with a NodeJs server i.e. the Platform. All you have to do is add your function to it. And wallah! you have an API endpoint..

What we wanted

Till now, we had two sources from where we got our quotes. One was via Ninja and the other was Gemini. Both of these requests originated from the client in React. We wanted to shift these to Netlify so that we could get a single Netlify endpoint instead. Netlify in turn will call these functions on its servers and give us the output.

Here is what we did

  1. Install Netlify’s npm package using npm install @netlify/functions
  2. Make a folder at /netlify/functions in our project root. Any file you put into this folder becomes an API endpoint that can be accessed at https://<domain>/.netlify/functions/<function>
import type { Context } from '@netlify/functions';
import { getQuoteFromNinja } from './ninja';
import { getQuoteFromGemini } from './gemini';

const quote = async (req: Request, context: Context) => {
let data;

if (req.method === 'OPTIONS') {
const res = new Response();

res.headers.set("Access-Control-Allow-Origin", "*");
res.headers.append("Access-Control-Allow-Headers", "*");
res.headers.append("Access-Control-Allow-Methods", "*");

return res;
}

if (Math.random() < 0.5) {
data = await getQuoteFromNinja();
} else {
data = await getQuoteFromGemini();
}

return Response.json({ data });
}

export default quote;

3. The OPTIONS is to overcome the CORS error that comes up when using the API from development environments.

4. Netlify has a section dedicated to Logs where you can get the function access logs

If you need more details, feel free to check out our commit. Happy coding!

--

--

Visakh Vijayan

Techie from Kerala, India. Days are for coding, nights for weaving tales of tech, travel, and finance. Join me in exploring this multifaceted journey