DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Netlify functions + custom Utils
James Foran
James Foran

Posted on

Netlify functions + custom Utils

In the beginning

Earlier this year I started to experiment with Netlify Functions. I was really excited at how easy the whole process was. However, when I went to use them in a live project I immediately wanted to share some code between functions. Coming coding c++ in Arduino, this was pretty easy. I wanted a similar experience in Node.

Being new to Node and JavaScript, it took me some time to find the solution that I thought was right for this situation.

I will take you through the most basic example, starting with a clean slate. The following assumes you have node, npm, and netlify dev installed in your pc.

Firstly though, what do I want to achieve. For the project in question, I have several functions that make calls to the Strava API. As part of this, I need to refresh the token. This is not something I wanted to do in each function, so, I needed to create some shared functionality, to ensure my code is DRY.

Netlify functions, as simple as can be.

The following

  1. First lets start a new project. Create a new project Directory. I have called mine
  2. Create a netlify.toml file, and a functions directory within project.
  3. Edit the netlify.toml file, and add the following lines

    [build]
        functions = "functions"
    
  4. create a hello-world.js file in the functions directory.

    exports.handler = (event, context, callback) => {
        return {
          statusCode: 200,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify('hello-world'),
        }
    }
    
  5. Lets test this quickly.

    Note, I am using windows terminal with wsl2.

  6. from the terminal of your project directory (not the function folder), run the command netlify dev. In a separate terminal, run netlify functions:invoke
    netlify dev function:invoke

  7. Accept the prompts, and you should should now see the function execute. Here is what it looks like for me...
    netlify dev function output
    In the first terminal, we have the console.log outputs, and in the second, we have the message "hello-world".

Netlify functions + a utility node module

Hopefully this has all worked out so far for you. If not, keep trying! We are not going to move onto the tricky part, building a node module. Its easier than you might think.

There are options within NPM to publish a module, but I want to develop side by side for now. Instead, I will create a local 'node module', that we can utilise in our hello-world file.

  1. create a utils folder, inside your functions folder.
  2. create apackage.json file. This can be done manually, or by running npm init in the directory. Note the src/index.js

    {
      "name": "utils",
      "version": "1.0.0",
      "description": "",
      "main": "src/index.js",
      "scripts": {
        "build": "npm run build"
      },
      "author": "james@flexion.tech",
      "license": "MIT"
    } 
    
  3. Now create a src directory. Within that directory, create an index.js file.

  4. Copy in the following code.

    Note, we are just using CommonJS modules here.

    module.exports.hello =  () => {
      console.trace()
      console.log("hello function")
      return "hello from utils"
    }
    
    module.exports.goodbye =  () => {
      console.trace()
      console.log("goodbye function")
      return "goodbye from utils"
    }
    
  5. Next, create a package.json file in the functions directory.. You can again use npm init as we did previously. The most important difference is the following addition:

      "dependencies": {
        "utils": "file:utils"
      },
    
  6. We are almost ready to put our fuctions to use, but there is one important last step. From the functions folder, we have to now run npm install. This is a one time thing only.

  7. Lets now update our hello-world.js file. One thing I like about this, is it does not expose the utility functions, and keeps everything in one place.

    const utils = require('utils')
    exports.handler = (event, context, callback) => {
      try {
        ...
        const message = {
          hello: utils.hello(),
          goodbye: utils.goodbye()
        }
        ...
        }
    }
    
  8. lets test

    1. Make sure netlify Dev is running.
    2. Lets run the function directly this time. this time run netlify functions:invoke hello-world --no-identity
  9. Review the output. You should see the object displayed in the invoke window, and a console.trace output in Netlify Dev

    netlify dev console.trace

that's a wrap...

Thanks for reading. If you found any mistakes, or have some further input, please let me know in the comments. There is also a repo on github if you want to check it out.

Top comments (0)

🌚 Life is too short to browse without dark mode