Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trying to use the OpenAI javascript API in react im facing this error: dangerouslyAllowBrowser #93

Open
ejgutierrez74 opened this issue May 18, 2024 · 2 comments

Comments

@ejgutierrez74
Copy link

Uncaught Error: It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the dangerouslyAllowBrowser option to true, e.g.,

new OpenAI({ apiKey, dangerouslyAllowBrowser: true });

https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
OpenAIError error.ts:5
OpenAI index.ts:134
ComponentChatBotReactChatBotifly.jsx:26
error.ts:5:6

My code .... (dont know if i can use:
new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); in ollama openai compatibility library javascript as there is nothing related in doc).

import ChatBot from 'react-chatbotify';
import OpenAI from 'openai';

const openai = new OpenAI({
    baseURL: 'http://localhost:11434/v1/',
    // required but ignored
    apiKey: 'ollama',
  })
  


let messageHistory = [];

async function fetchData() {
    const chatCompletion = await openai.chat.completions.create({
        messages: messageHistory,
        model: 'llama3',
      })
      return chatCompletion.data.choices[0].message.content;
/*
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
        const data = await response.json();
        return data.title;
    } catch (error) {
        return "Oh no I don't know what to say!";
    }
*/
}

function updateMessages( rol, content) {
    messageHistory.push({ role: rol, content: content });
    return messageHistory;
}
export default function ComponentChatBotReactChatBotifly() {


    const flow = {
        start: {
            message: (params) => {
                updateMessages('system','You are a helpful assistant. You are here to help the user with their queries. Be kind and short in your responses.');
                params.injectMessage("Hi my name is Edubot. Im here to help you");
                params.injectMessage("Can you write your username, so i can address you ?");
                updateMessages('assistant','Hi my name is Edubot. Im here to help you');
                updateMessages('assistant','Can you write your username, so i can address you ?');
            },
            path: "askname"
        },
        askname: {
            message: (params) => {
                updateMessages('user',`${params.userInput}`);
                params.injectMessage(`Nice to meet you ${params.userInput}!`);
                updateMessages('assistant',`Nice to meet you ${params.userInput}!`);
                params.injectMessage("Ask anything i will try to help you!");
                updateMessages('user','Ask anything i will try to help you!');
            },
            path: "loop",
        },
        loop: {
            message: async (params) => {
                updateMessages('user',`${params.userInput}`);
                const result = await fetchData();
                return result;
            },
            path: "loop",
        }
    }
    return (
        <ChatBot options={{ theme: { embedded: false }, chatHistory: { storageKey: "example_simulation_stream" }, botBubble: { simStream: true } }} flow={flow} />
    )
}`

Update tried to use the dangerouslyAllowBrowser option to true:

const openai = new OpenAI({
    baseURL: 'http://localhost:11434/v1/',
    // required but ignored
    apiKey: 'ollama',
    dangerouslyAllowBrowser: true   
  })

Seems i skip or pass the error of the issue, but still doesnt work as im facing:

Solicitud de origen cruzado bloqueada: La política de mismo origen (Same Origin Policy) no permite la lectura de recursos remotos en http://localhost:11434/v1/chat/completions. (Motivo: La cabecera ‘x-stainless-arch’ no está permitida de acuerdo a la cabecera ‘Access-Control-Allow-Headers’ de la verificación previa de la respuesta CORS).

In english ( using Google Translator) :
Request for blocked cross origin: the same origin policy (Same Origin Policy) does not allow reading remote resources at http: // localhost: 11434/v1/chat/complete. (Reason: The header ‘X-Stainless-Arch’ is not allowed according to the header ‘Access-Control-Allow-Headers’ of the previous verification of the Cors response).

@rayhu
Copy link

rayhu commented May 20, 2024

This is because this React component runs on the client side. If anyone looks at the page source code, your API key will leak. Please move this code to the back-end. Create an API in the way described in this post:

https://dev.to/bilal1718/how-to-create-a-backend-api-in-express-js-e0k

@ejgutierrez74
Copy link
Author

But i know is not the perfect place..but should give a warning not error that stops everything.

By the way im using react + vite...so in my project i can create only a folder as the document says and it would work ? Or is better with react using Next.js ???

By now i success storing the api_key in .env files in client side...would be great in i could encrypt that file....but i dont know how...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants