The code executes smoothly on my local machine, but encounters an error on Heroku: [TypeError: An invalid character is present in the header content ["Authorization"]] {error code: 'ERR_INVALID_CHAR'}

I am currently working on a chatbot project that utilizes the openAI API to generate responses based on specific prompts related to a particular topic. Everything works perfectly when I test the code on my local machine. However, upon deploying it to Heroku, I encountered the following error:

error [TypeError: Invalid character in header content ["Authorization"]].

I attempted to include an authorization header in the fetch() POST request, but unfortunately, the error persists. I am unsure of the source of this issue. Any insights on where this error might be originating from?

try {
      fetchEventSource('/api/chat', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${encodedApiKey}`,
        },

        body: JSON.stringify({
          question,
          history,
        }),
        signal: ctrl.signal,
        onmessage: (event) => {
          if (event.data === '[DONE]') {
            setMessageState((state) => ({
              history: [...state.history, [question, state.pending ?? '']],
              messages: [
                ...state.messages,
                {
                  type: 'apiMessage',
                  message: state.pending ?? '',
                  sourceDocs: state.pendingSourceDocs,
                },
              ],
              pending: undefined,
              pendingSourceDocs: undefined,
            }));
            setLoading(false);
            ctrl.abort();
          } else {
            const data = JSON.parse(event.data);
            if (data.sourceDocs) {
              setMessageState((state) => ({
                ...state,
                pendingSourceDocs: data.sourceDocs,
              }));
            } else {
              setMessageState((state) => ({
                ...state,
                pending: (state.pending ?? '') + data.data,
              }));
            }
          }
        },
      });
    } catch (error) {
      setLoading(false);
      setError('An error occurred while fetching the data. Please try again.');
      console.log('error', error);
    }
  }

The fetch request above is where I suspect the error might be originating from, particularly in the headers section. Despite setting up the configuration variables on Heroku, the issue persists and I am unable to find a resolution.

Answer №1

There doesn't seem to be any problem with your syntax. If it's working fine locally, the issue might be related to the configuration variables, especially if you haven't defined the encodedApiKey. It's important to ensure that the relationship is properly set up. Unfortunately, I don't have experience with Heroku so without more information, it's difficult to pinpoint the exact issue. Just make sure that your code can access your configuration variables smoothly.

Answer №2

It seems that the value stored in encodedApiKey is not correct. To verify this, you can print it out to ensure it's accurately defined. It should follow the format of sk-somethingVeryLong

If you are using Heroku, you have the option to configure your environment variables either through their CLI.

heroku config:set OPENAI_API_KEY=sk-something

Alternatively, you can also set them up via your project settings https://i.sstatic.net/vdfvd.png

Within your code, you will be able to retrieve the value of this environment variable by calling process.env.OPENAI_API_KEY.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of duplicated HTML IDs arises when implementing conditional rendering in NextJS components

I am currently utilizing NextJS in my project. One of the components I'm working with is a support component designed to render a single row: const SingleRow = ({ id, label, children }) => { return ( <p id={id}> <span>{label}< ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

Tips for composing content on a sanitized input?

In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this: The {0} {1} {2} his {3} off To achieve this functionality, I wrote the f ...

Can you explain the purpose of the curly braces found in a function's parameter definition?

I am currently working on an Angular 5 project and came across this intriguing Typescript code snippet. (method) CreateFlightComponent.handleSave({ currentValue, stepIndex }: { currentValue: Partial<Flight>; stepIndex: number; }): void Can ...

Is there a way to turn off eslint's no-promise-executor-return rule?

Can the eslint rule 'no-promise-executor-return' be disabled? my .eslintrc file { "env": { "es6": true, "node": true }, "extends": [ "airbnb-base" ], "globals": { "de ...

What is the procedure for accessing a namespace when declaring it globally?

Website Project Background Currently, I am working on a simple website where users can update their pictures. To achieve this functionality, I am utilizing the Multer library along with Express in Typescript. Encountered Issue I am facing a challenge re ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

What causes the error when I use "use client" at the top of a component in Next.js?

Whenever I include "use client" at the top of my component, I encounter the following error: event - compiled client and server successfully in 2.5s (265 modules) wait - compiling... event - compiled client and server successfully in 932 ms (265 modules) ...

The Strapi backend is experiencing issues retrieving images, however, all other data fields are functioning correctly

Currently, I'm working on developing an Ap using nextjs as the frontend and strapi as the backend. The home page is functioning properly with all product details like thumbnails, titles, subtitles, prices, etc., being displayed correctly. However, wh ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Angular Material's autocomplete feature allows users to easily search

I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field. However, my next task is to enable filtering of the ...

Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process. The TypeScript co ...

Open in a new tab for enhanced content formatting in Prismic on NextJs

In my Prismic RichText editor, I have included two files (terms and conditions) that I would like to open in a new tab. Unfortunately, Prismic does not offer an option like target _blank for this functionality. I am currently working with NextJs and Tail ...

Error encountered while attempting to load an image in a React component using TypeScript linting

I am currently working on a React app with Next.js where I have imported an image using the following code: import image1 from '../../../img/dummy-image-2.jpg'; Subsequently, I use the image in my app like so: <img src={image1} alt="Dumm ...

Struggles with updating app.component.ts in both @angular/router and nativescript-angular/router versions

I have been attempting to update my NativeScript application, and I am facing challenges with the new routing system introduced in the latest Angular upgrade. In my package.json file, my dependency was: "@angular/router": "3.0.0-beta.2" After the upg ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have ...

Monitor the change in values upon pressing the submit button on Angular

I am currently working with an edit form that contains data in the input fields. <ng-form #infoForm="ngForm" novalidate> <div> <label for="firstName">First Name :</label> <input type=" ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Determine the generic parameter of the output type by analyzing the resolved value of a data type within the function

I am looking to automatically determine the generic parameter of the return type by utilizing the resolved value of a type within the function. Consider the following: export type Context = any; export type Handler<T> = (ctx: Context) => Promise& ...

Encountered a 401 error with NextJS and the "openai api" when calling the createChatCompletion() endpoint, but received a 200 ok response when calling create

A Short Summary When using NextJS api router, the call to openai api endpoint createChatCompletion() failed. However, it was successful when done with pure Node.js code. More Details I attempted to use NextJS's api router as demonstrated here for ca ...