Can't access OPENAI_API_KEY after deploying

So my project works perfect in development, but whenever I publish it, I get this error: OpenAI API key is missing. Pass it using the ‘apiKey’ parameter or the OPENAI_API_KEY environment variable.

I understand that in order to not use NEXT_PUBLIC in your variable for keys it needs to be accessed server side, and I’ve prompted v0 to do this many times, but we seem stuck on this.

Here is my V0 project:
https://v0.dev/chat/room-analyzer-art-recommendation-iUsiPzinbs5?b=b_S8wzitSTpQA

Here is my deployed project:

Here is my RoomAnalysis code

import { generateText } from "ai"
import { openai } from "@ai-sdk/openai"
import type { RoomAnalysis } from "../types/roomAnalysis"
import { compressImage } from "../utils/imageProcessing"

export async function analyzeRoom(image: File): Promise<RoomAnalysis> {
  try {
    const compressedImage = await compressImage(image)

    const prompt = `Analyze this room image and return ONLY a JSON object without any explanation or markdown formatting. Provide detailed and varied responses for each category:

{
  "style": {
    "primary": ["string"],
    "secondary": ["string"],
    "era": "string",
    "description": "string"
  },
  "colors": {
    "dominant": [{"name": "string", "hex": "string"}],
    "accent": [{"name": "string", "hex": "string"}],
    "overall_palette": "string"
  },
  "lighting": {
    "type": "string",
    "intensity": "number (1-10)",
    "temperature": "string",
    "description": "string"
  },
  "space": {
    "size": "string",
    "proportions": "string",
    "ceiling_height": "string"
  },
  "furnishings": ["string"],
  "textures": ["string"],
  "mood": {
    "primary": ["string"],
    "secondary": ["string"],
    "description": "string"
  },
  "art_considerations": {
    "suitable_styles": ["string"],
    "recommended_sizes": ["string"],
    "potential_themes": ["string"],
    "placement_suggestions": ["string"]
  },
  "overall_impression": "string"
}

Provide varied and nuanced analysis, considering subtle details and potential artistic interpretations of the space. Aim for a rich, descriptive response that captures the essence of the room and its potential for art display.

Image: ${compressedImage}`

    const { text } = await generateText({
      model: openai("gpt-4o-mini"),
      prompt: prompt,
      maxTokens: 500,
    })

    // Extract JSON from the response
    let jsonString = text

    // If the response contains markdown code blocks, extract the JSON
    if (text.includes("```")) {
      const match = text.match(/```(?:json)?\s*([\s\S]*?)\s*```/)
      if (match && match[1]) {
        jsonString = match[1].trim()
      }
    }

    try {
      const analysis: RoomAnalysis = JSON.parse(jsonString)
      return analysis
    } catch (parseError) {
      console.error("JSON Parse Error:", parseError)
      throw new Error("Failed to parse room analysis results. Please try again.")
    }
  } catch (error) {
    console.error("Error analyzing room:", error)

    // Handle specific error cases
    if (error instanceof Error) {
      if (error.message.includes("503")) {
        throw new Error("Service temporarily unavailable. Please try again in a few moments.")
      }
      if (error.message.includes("context_length_exceeded")) {
        throw new Error("Image is too large to process. Please try a smaller image.")
      }
      throw error
    }

    throw new Error("Failed to analyze room. Please try again.")
  }
}

Hey! Have you set the api key in your project on Vercel?

1 Like

Yes. It’s both in Vercel and V0 environment variables. That’s whats confusing

Just did a quick dive into the code and it looks like the issue is that your AI functions (files in the lib folder) are running on the client. As you’ve said and understood, you can’t access server-side secrets on the client. I’d suggest either 1) adding “use server”; to the top of each file to turn them into server actions (functions will run on the server and therefore access your env variables); or move them into route handlers (API routes) and call them with fetch requests.

Remember to add some kind of auth check to ensure you’re protecting the access to the function!

More info on server actions here: Data Fetching: Server Actions and Mutations | Next.js

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.