Smallest Netlify Functions code example
On This Page
All existing Netlify Functions examples are shared functions + frontend codebase.
But it's also possible to have a repo with only the serverless functions.
I just cloned an existing NF repo to explore how it works, but I got distracted/sidetracked figuring out which dependencies are for its CRA frontend, which ones are for the functions. I made a minimal repro of the functions only.
File structure:
. # project root
├── build/
│ └── index.html
├── functions/
│ └── hello.js
├── netlify.toml
└── package.json
Netlify config netlify.toml
:
[build]
functions = "functions"
publish = "build"
Corresponds to these directory names:
functions
= directory containing our function script (eg.hello.js
)build
= directory containing the static file- In this case, it's a regular HTML file. This can also contain the static build result from CRA, Svelte, etc.
When we run ntl dev
, Netlify serves our static HTML file eg. on localhost:8888
and our functions on localhost:8888/.netlify/functions/{FUNCTION_FILE_NAME}
.
We don't need to add any dependencies or command (unless we need them for our functions).
{
"name": "smol-netlify-functions",
"version": "1.0.0",
"main": "index.js",
"scripts": {},
"license": "ISC"
}
Example code
build/index.html
<h1>minimal Netlify Functions example</h1>
<div id="response">loading...</div>
<script>
const FUNCTIONS_URL = "/.netlify/functions/hello/";
fetch(FUNCTIONS_URL)
.then((response) => response.json())
.then((data) => {
document.getElementById("response").innerText = data;
});
</script>
functions/hello.js
exports.handler = async () => {
return {
statusCode: 200,
body: JSON.stringify("Hello there! This message is sent from Netlify Functions."),
};
};
Run it
ntl dev
localhost:8888
— our HTML pagelocalhost:8888/.netlify/functions/hello
— our function endpoint- Since this is a GET request, we can open this directly in the browser
Repo: https://github.com/ekafyi/smol-netlify-functions
References:
In: