DEV Community

Kehinde Adeleke
Kehinde Adeleke

Posted on

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:


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.

Discussion (0)