DEV Community

Kehinde Adeleke
Kehinde Adeleke

Posted on

1

How to Fix error with openai in your nodeJS app

I was trying out openAI's api when I came across this error.

cannot import module

It was quite annoying. To solve it, you add the "type": "module" to your package.json file.

If you don't have a package.json file, use npm init -y" to create one.

With that, you should have this:
type module

which should solve it.

but...something else might come up. Since you need your API key in a .env file to access the api, you would need to import the dotenv package.

after installing with npm or yarn, I used the require keyword to import it:

require('dotenv').config();

For some reason, that seems to throw another error:

cannot use require

It was very frustrating and stack overflow didn't seem to have a direct answer.

To solve it, change require to a normal import statement,

in this case it would be, import dotenv from 'dotenv/config'

the final code looks like this:

Image description

everything works

with that, you are done.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay