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.
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:
// .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 })
}
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 })
}
deno.json
file.{
"imports": {
"foo": "./utils/sum.js"
}
}
[functions]
deno_import_map = "./deno.json"
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.