简体   繁体   中英

Module not found: Can't resolve 'net' when i importing twilio shows,Nextjs error

Console

1个

I started to learn Next.js. When i import Twilio, it shows errors "fs not found.net not found"

./node_modules/https-proxy-agent/dist/agent.js:15:0
Module not found: Can't resolve 'net'

    Import trace for requested module:
    ./node_modules/https-proxy-agent/dist/index.js
    ./node_modules/twilio/lib/base/RequestClient.js
    ./node_modules/twilio/lib/index.js
    ./components/Login/ForgotPassword.jsx
    ./components/Login/Login.js
    ./pages/login/index.js
    
    https://nextjs.org/docs/messages/module-not-found

Since version 5, Webpack doesn't include polyfilles for node libraries.

Adding the following Webpack config in your next.config.js should do the trick:

const nextConfig = {
  ...
  webpack: config => {
    config.resolve.fallback = { ...config.resolve.fallback, net: false, os: false };
    return config;
  },
  ...
}

I know Next.js runs code on both the client and server side, but this looks like you are trying to use the Twilio library in the client. The Twilio library is not built to be used in the client side and this is expected behaviour.

If you try to make calls to the Twilio API from the front end, you will expose your Account SID and Auth Token, which could be taken by a malicious user and used to abuse your account.

Instead, you should make calls to the Twilio API on the server side and make requests from your front end to your own server to do so.

Here's an example of sending an SMS from React with Twilio (though not with Next.js) that I wrote and here's a blog post that looks like it shows what you should do, by creating an API route in Next.js to send an SMS with Twilio . Whatever you are hoping to do with the API, those posts should give you an idea how to approach it.

You are running code on the client. Or at least nextjs is thinking that you are running code on the client. Try to follow the stack trace and see how you are calling the code that is importing net .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM