You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth

const url = "https://api.openai.com/v1/chat/completions"
const headers = {
            'Content-type': 'application/json;charset=UTF-8',
            'Authorization': `Bearer ${apiKey}`,
        }
const data = {
            "model": "gpt-3.5-turbo-1106",
            "messages": [
                {
                    "role": "user",
                    "content": "this is a test message"
                }
            ],
            "max_tokens": 45,
            "temperature": 0.7
        }

await axios.post(url, data, headers)
            .then((response) => {
                console.log(response)
                setChatLog((prevChatLog) => [...prevChatLog, { type: 'bot', message: response.data.choices?.[0].message?.content }])
            })
            .catch((error) => {
                console.error(error)
            })

I’m trying to get chat responses here, but code always gives me error 401, unauthorised.
But while checking the API endpoint on Postman, everything works fine.

The error shows this “message”: "You didn’t provide an API key. You need to provide your API key in an Authorization header using Bearer auth … ",
What could possibly be wrong here?

Welcome to the forum.

Receiving a 401 Unauthorized error in your code but not in Postman suggests there might be an issue with how the API key is being handled in your JavaScript code. Here are some steps to troubleshoot and resolve this issue:

  1. Check the API Key Variable: Ensure that the apiKey variable in your code actually contains the correct API key. It’s possible that the environment or context in which you’re running this code doesn’t have access to the variable, or it’s not being set correctly.
  2. Inspect Headers: The way headers are set in your code seems correct, but double-check if apiKey is properly populated. You can add a console.log(apiKey) before the axios call to verify that the key is what you expect.
  3. Environment Differences: There might be differences in how environments (your JavaScript runtime vs Postman) handle headers or environment variables. Ensure that the environment where your JavaScript code runs has access to the apiKey variable.
  4. CORS Policy: If you’re running this code in a browser environment, Cross-Origin Resource Sharing (CORS) policies might prevent the browser from sending the header correctly. However, this would typically result in a different error.
  5. Proxy Issues: If you’re behind a proxy, it might strip out or modify headers. This is less likely but worth considering if you’re in a corporate or restricted network environment.
  6. Syntax Check: Double-check the syntax and structure of your axios request. It looks correct, but a small typo could cause issues.
  7. Use Environment Variables: If you’re not already doing so, store your API key in an environment variable rather than hardcoding it in your script. This is a best practice for security reasons.
  8. Test with Hardcoded Key: As a test (but not a permanent solution), try replacing ${apiKey} with the actual key string directly in the code. If this works, the issue is likely with how apiKey is being set.
  9. Compare with Postman Request: Finally, compare the request as it’s sent from your JavaScript code with how it’s sent from Postman. You can inspect the network tab in your browser’s developer tools to see the outgoing request details.

Remember, for security reasons, never expose your API keys in client-side code if this code is intended for a browser environment. Always keep keys server-side or in a secure environment. – ChatGPT 4

1 Like

Welcome to the dev forum @tripathipranav14

Here’s the syntax for the cURL request:

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'

make sure that the apiKey is initialized and holds a value.

1 Like

Thank you for replying :slight_smile:

  • I’ve console logged apiKey and it shows the correct value.
  • After checking the error response from axios, it shows that the config sent was actually correct.
  • How can I check for CORS policies? As this code is in a nextjs app.
  • I even tried hardcoding the api key, but it still show error 401 (unauthorised)

Thank you!
But I’m using this code in nextjs app and If it is possible to use cURL in nextjs, please let me know about it.
Everything seems fine but the error still persists.

Thanks for the info. The error is likely in your code where headers is being passed to the axios.post() method.

This is how headers should be passed:

axios.post(url, data, {
    headers: headers
});

If that doesn’t work, consider using the official NodeJS OpenAI package.

1 Like

Thank you for all of your suggestions and replies.
After a bit of reaseach I got the solution from Postman itself.

let data = JSON.stringify({
            "model": "gpt-3.5-turbo-1106",
            "messages": [
                {
                    "role": "user",
                    "content": "your message here",
                }
            ],
            "max_tokens": 2048,
            "temperature": 0.7
        });

        const apiKey = "paste your api key here or you can use env variables"

        let config = {
            method: 'post',
            maxBodyLength: Infinity,
            url: 'https://api.openai.com/v1/chat/completions',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`,
            },
            data: data
        };

        setLoading(true)

        axios.request(config)
            .then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error);
            });
    }

Thank you for helping.
Hope this helps somone.

1 Like

@tripathipranav14

Is it OK if a moderator closes this topic?

Sure, @EricGT
Thanks for helping