- Create a
/netlify
folder and inside create/functions
folder, and inside create a.js
file for your function - OPTIONAL: require MongoClient if you are using MongoDB
- Create an async function named
handler
- OPTIONAL: Connect to the database, get your data, then close DB connection
- Return an object with
statusCode
,headers
(optional), andbody
properties
Created
March 31, 2024 15:35
-
-
Save Kernix13/cd5908cfc3ffac819bc451a20ea40ac8 to your computer and use it in GitHub Desktop.
Netlify function example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment