Netlify Dev – Deploying Functions

Netlify Dev is a new command line tool from Netlify that lets you reproduce some of Netlify’s functionality locally. This includes:

  • routing
  • edge logic
  • running lambda fucnctions
  • pulling environment variables from Netlify
  • deploying directly to production
  • live deployments

You can create a new function like so

netlify functions:create some-func

Example project layout

/functions
  /src
    /some-func
      package.json
  / build
netlify.toml
package.json

In your netlify.toml file

[dev]
  functions = "functions/src"

[build]
  functions = "functions/build"

To run locally

netlify dev

To run and build, add these to your package.json file

"scripts": {
  "build": "ENV=production ./build.sh",
  "gatsby": "gatsby",
  "gatsby:build": "gatsby build"
}

Then create your build script. Building and deploying functions can be a little tricky. By default Netlify won’t install your function’s project dependencies. If your functions are in JavaScript, and they have dependencies, then you will need to install these dependencies for each function so Netlify can build and deploy each function.

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

# Netlify lambda functions
# need to npm install for each function's package.json otherwise functions won't build

cd functions/src/
for f in *; do
  if [ -d ${f} ]; then
    echo "Running npm install for package: $f"
    cd "$f"
    npm install
    cd ..
  fi
done

cd ../..

# remove old functions/build directory
rm -rf functions/build

# build the functions 
npx netlify functions:build --src functions/src --functions functions/build

# build the reset of your site
npm run gatsby:build

Then when you deploy to Netlify via GitHub/GitLab/Bitbucket etc. by default Netlify will build your project.

Another way to deploy is using

netlify deploy --prod

or stream live deployment

netlify dev --live