Import Nuxt3 utility function into Netlify Edge Function

81 Views Asked by At

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.

1

There are 1 best solutions below

0
dbzx10299 On BEST ANSWER

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

  • at the root of the project create a deno.json file.
{
  "imports": {
    "foo": "./utils/sum.js"
  }
}
  • Then at the root in netlify.toml we need the path to the import map
[functions]
  deno_import_map = "./deno.json"
  • Lastly in netlify/edge-functions/foo.js
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.