How to correctly import axios and use in functions (vue/vite)

Hi all, hoping to resolve this issue and help anyone else having the same.

I’ve got a vue/vite site. im trying to use serverless functions and i need axios. i thought a simple require would work, and it does locally but in prod this is the error,

Runtime.ImportModuleError - Error: Cannot find module 'axios'

here is my sample functions file:

const axios = require('axios')

const API_ENDPOINT = 'https://catfact.ninja/fact'

export async function handler(event, context) {
  let response
  try { response = await axios.get(API_ENDPOINT) }
  catch (err) {
    return {
      statusCode: err.statusCode || 500,
      body: JSON.stringify({
        error: err.message
      })
    }
  }

  return {
    statusCode: 200,
    body: JSON.stringify(response.data)
  }
}

so my question is this, how do i import axios and use in functions? im assuming the build process on node for functions isn’t installing axios as a dependency for some reason. Do i need to add external deps as a plugin for the netlify build process somewhere? i appreciate all the help. The guides are helpful and i think this issue is perhaps build specific. thank you in advance.

netlify.toml config

[build]
  functions = "functions"

[[redirects]]
  from = "/api/*"
  to = "/.netlify/functions/:splat"
  status = 200

[[redirects]]
  from = "/*"
  to = "index.html"
  status = 200

Did you try using import axios from 'axios'?

hi @hrishikesh !

Yes i did, same error after deploying to prod. Works fine locally both ways.

Merry Christmas, thanks for the reply!

Feel free to share the repo, because this is supposed to work both ways, for example:

Right, i would think so too.

Here is the repo: https://github.com/hellozoran/zm-2022

Submitted a fix:

https://github.com/hellozoran/zm-2022/pull/7

Ahh, that is how to set the bundler, got it! I’ll leave this here in case anyone has the same issue

i had tried adding the bundler option under the build settings which didn’t work, like this:

[build]
  functions = "functions"
  node_bundler = "esbuild"

but it should be

[build]
  functions = "functions"
[functions]
  node_bundler = "esbuild"

Thanks for your help! Much appreciated.

For better readability, you can also keep functions entirely separate, for example:

[functions]
  directory = "functions"
  node_bundler = "esbuild"

or if you saved your functions in netlify/functions, you can exclude the directory part altogether.

2 Likes

Good to know! I was looking for docs on all the different config options. This is super helpful, appreciate it