javascriptnuxt.jsnetlifynuxt3.jsnetlify-function

Import Nuxt3 utility function into Netlify Edge Function


How can I import a utility function from the utils directory into my edge function in Nuxt3?

If I have a function sum in /utils/sum.js

export const sum = (…nums) => nums.reduce((prev, current) => prev + current)

And an edge function in netlify/edge-functions/foo.js

const result = sum(1, 2, 3)

export default () => {
  return Response.json({ sum: result })
}

export const config = {
  path: '/foo'
}

This breaks and sum is not defined. I am able to import bare modules into the edge function but I can‘t import my own utility functions.

I am also running netlify dev from the terminal since starting nuxt with npm run dev will not load the functions.


Solution

  • In Nuxt 3, utils is a folder that is scanned and has auto imports feature by default. If you are using netlify edge functions you have to be careful how you import the utility function into your edge function file and it will work just fine.

    Note that at the project root we have this folder structure:

    |-- netlify
        |-- edge-functions
            |-- foo.js
    |-- utils
        |-- sum.js
    

    Below are three examples:

    Direct Import

    // .js file extension must be included
    import { sum } from '../../utils/sum.js'
    
    export default async (req, context) => {
      const result = sum(2, 3, 4)
      return Response.json({ sum: result })
    }
    

    Dynamic Import

    export default async (req, context) => {
      // .js file extension must be included
      const { sum } = await import('../../utils/sum.js')
      const result = sum(2, 3, 4)
      return Response.json({ sum: result })
    }
    

    Import Map

    {
      "imports": {
        "foo": "./utils/sum.js"
      }
    }
    
    [functions]
      deno_import_map = "./deno.json"
    
    import { sum } from 'foo'
    export default async (req, context) => {
      const result = sum(2, 3, 4)
      return Response.json({ sum: result })
    }
    

    Lastly run netlify dev and you can test the edge functions.