Skip to content

Instantly share code, notes, and snippets.

@Kernix13
Created March 31, 2024 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kernix13/cd5908cfc3ffac819bc451a20ea40ac8 to your computer and use it in GitHub Desktop.
Save Kernix13/cd5908cfc3ffac819bc451a20ea40ac8 to your computer and use it in GitHub Desktop.
Netlify function example
// Add your MongoDB connection string into an environment variable
const { MongoClient } = require("mongodb");
// It's common to pass arguments to 'handler' of event, context
const handler = async () => {
// Optional MongoDB connection, collection name = "pets"
const client = new MongoClient(process.env.CONNECTIONSTRING);
await client.connect();
const pets = await client.db().collection("pets").find().toArray();
// Close connection to DB so the Function can finish:
client.close();
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(pets)
};
};
module.exports = { handler };

Structure of a Netlify Function

  1. Create a /netlify folder and inside create /functions folder, and inside create a .js file for your function
  2. OPTIONAL: require MongoClient if you are using MongoDB
  3. Create an async function named handler
  4. OPTIONAL: Connect to the database, get your data, then close DB connection
  5. Return an object with statusCode, headers (optional), and body properties
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment