Next.js Module not found: Can't resolve 'tls'

Viewed 4036

I am trying to add instagram feed to my next.js app, so I installed instagram-web-api, but when I do import Instagram from "instagram-web-api", it gives me a lot of errors(Can't resolve 'tls', Can't resolve 'fs', etc).

I can use other library just fine with npm install & import, but I am not sure why "instagram-web-api" giving me all this errors.

So I searched on internet for solution and saw feedback to add the below code to the next.config.js.

module.exports = { webpack5: true,
  webpack: (config) => {
    config.resolve.fallback = { tls: false };

    return config;
  },
};

So, I replaced module.exports = nextConfig; with this code, deleted and reinstalled the library again, then it gives me another bunch of errors (Can't resolve 'stream', Can't resolve 'buffer', Can't resolve 'process', Can't resolve 'cypto', etc).

I don't have a lot of knowledge on webpack, I'm used to using just the default setting of next.js, so I am not sure what's going on :(

1 Answers

Instagram-web-api is a node js module and you are trying to use it on the frontend. You should move all your instagram-web-api code to the getStaticProps like this

export async function getStaticProps(context) {
    const client = new Instagram({ username: 'INSTAGRAM_USERNAME', password: 'INSTAGRAM_PASSWORD' });
    await client.login();

    const response = await client.getPhotosByUsername({
        username: 'INSTAGRAM_USERNAME',
    });

    return {
        props: {
            posts: response.user.edge_owner_to_timeline_media.edges,
        }, // will be passed to the page component as props
    };
}
Related