Skip to content

api/image/generate - generate an image#1

Merged
sweetmantech merged 7 commits intomainfrom
sweetmantech/myc-3545-apiimagegenerate-generate-an-image
Nov 27, 2025
Merged

api/image/generate - generate an image#1
sweetmantech merged 7 commits intomainfrom
sweetmantech/myc-3545-apiimagegenerate-generate-an-image

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented Nov 27, 2025

Summary by CodeRabbit

  • New Features

    • Image-generation API endpoint with prompt handling and CORS preflight support
  • Improvements

    • Clearer client-facing error responses for missing prompts and generation failures
    • Updated image-generation request/response behavior
  • Chores

    • Added AI SDK dependencies and image-generation utility
    • Adjusted TypeScript configuration
  • Removed

    • Protected page previously displaying gated content has been removed

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Nov 27, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
recoup-api Ready Ready Preview Nov 27, 2025 8:13pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 27, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a CORS-aware image-generation API route (OPTIONS + GET) that validates a prompt, calls a new generateImage helper (wrapping the experimental OpenAI image API), returns structured JSON results/errors, introduces two AI SDK dependencies, and updates tsconfig formatting and JSX transform.

Changes

Cohort / File(s) Summary
API Endpoint & CORS
app/api/image/generate/route.ts
Added OPTIONS handler for CORS preflight. Replaced static GET with GET(request: NextRequest) that extracts/validates prompt, calls generateImage(prompt), and returns JSON { result } or { error } with appropriate 400/500/200 status codes; all responses include CORS headers.
AI Integration Module
lib/ai/generateImage.ts
New default export generateImage(prompt: string): Promise<Experimental_GenerateImageResult | null> that calls experimental_generateImage using provider model gpt-image-1 (via @ai-sdk/openai) with quality: "high", returns the API result and logs errors (returns null/undefined on failure).
Dependencies
package.json
Added runtime dependencies: @ai-sdk/openai@3.0.0-beta.71 and ai@6.0.0-beta.122.
TypeScript Config
tsconfig.json
Reformatting of arrays/blocks, changed JSX transform from preserve to react-jsx, added .next/dev/types/**/*.ts to include, and expanded explicit exclude/paths formatting (no API surface changes).
Removed UI Page
app/protected/page.tsx
Deleted default-exported ProtectedPage React component and its JSX.
Middleware API Schema
middleware.ts
Renamed output schema to imageGenerateOutputSchema, replaced prior weather output with image result shape (images array + usage), changed query param doc from location to prompt, removed /protected middleware block, and updated /api/image/generate pricing/description/output schema.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant NextRoute as Next.js Route
  participant GenFn as generateImage()
  participant OpenAI as OpenAI Experimental API

  Client->>NextRoute: OPTIONS /api/image/generate (preflight)
  Note right of NextRoute: respond with CORS headers
  NextRoute-->>Client: 204 + CORS

  Client->>NextRoute: GET /api/image/generate?prompt=...
  NextRoute->>NextRoute: validate prompt
  alt missing prompt
    NextRoute-->>Client: 400 { error } + CORS
  else prompt present
    NextRoute->>GenFn: generateImage(prompt)
    GenFn->>OpenAI: experimental_generateImage(model: gpt-image-1, prompt, quality: high)
    OpenAI-->>GenFn: image result / error
    alt success
      GenFn-->>NextRoute: result
      NextRoute-->>Client: 200 { result } + CORS
    else failure
      GenFn-->>NextRoute: null / error
      NextRoute-->>Client: 500 { error } + CORS
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–30 minutes

  • Pay extra attention to:
    • app/api/image/generate/route.ts: CORS header coverage on all branches, correct use of NextRequest, and explicit status/JSON shapes.
    • lib/ai/generateImage.ts: ensure errors return a clear value (null) vs implicit undefined; verify correct import/use of the experimental API and providerOptions.
    • package.json dependency additions: confirm intended SDK versions and any required runtime configuration.
    • tsconfig.json: JSX transform change impact on existing JSX/TSX compilation.

Possibly related PRs

Poem

🐇 I nibbled a prompt beneath the moonlit log,

whiskers twitch, pixels bloom from a tiny cog,
I hopped, I hummed, the canvas turned bright—
carrots and code made an image tonight. ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: implementing an image generation endpoint at api/image/generate with appropriate handlers, error handling, and CORS support.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sweetmantech/myc-3545-apiimagegenerate-generate-an-image

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
app/api/image/generate/route.ts (1)

23-36: Consider adding prompt length validation and using POST instead of GET.

Two considerations for this endpoint:

  1. HTTP method: GET is typically for idempotent retrieval operations. Image generation is a resource-intensive operation with potential costs. POST is more semantically appropriate and avoids URL length limits for long prompts.

  2. Prompt validation: Consider adding a maximum length check to prevent abuse with extremely long prompts.

Example length validation:

     if (!prompt) {
       return NextResponse.json(
         { error: "prompt query parameter is required" },
         {
           status: 400,
           headers: getCorsHeaders(),
         },
       );
     }
+
+    if (prompt.length > 4000) {
+      return NextResponse.json(
+        { error: "prompt exceeds maximum length of 4000 characters" },
+        {
+          status: 400,
+          headers: getCorsHeaders(),
+        },
+      );
+    }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 31f2bfd and 7c1c179.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • app/api/image/generate/route.ts (1 hunks)
  • lib/ai/generateImage.ts (1 hunks)
  • package.json (1 hunks)
  • tsconfig.json (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
app/api/image/generate/route.ts (1)
lib/networking/getCorsHeaders.ts (1)
  • getCorsHeaders (6-12)
🔇 Additional comments (4)
tsconfig.json (1)

1-42: LGTM!

The TypeScript configuration changes are appropriate. The jsx: "react-jsx" setting aligns with the modern React 17+ JSX transform, and including .next/dev/types/**/*.ts is standard for Next.js projects.

app/api/image/generate/route.ts (3)

10-15: LGTM!

The OPTIONS handler correctly implements CORS preflight response with appropriate headers.


38-56: LGTM on error handling flow.

The handler correctly checks for null results from generateImage and returns appropriate error responses. Once the critical issue in lib/ai/generateImage.ts is fixed, this flow will work as intended.


57-69: Error handling is well-implemented.

The catch block properly extracts error messages and avoids leaking stack traces while providing useful error information.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
middleware.ts (1)

70-73: Remove /protected/:path* from the middleware matcher.

The protected directory and all related routes have been removed from the codebase. No remaining references to /protected paths exist. This matcher entry should be removed to avoid unnecessary middleware invocations:

export const config = {
  matcher: ["/api/:path*"],
  runtime: "nodejs",
};
🧹 Nitpick comments (2)
middleware.ts (1)

38-41: Consider defining usage properties for better discoverability.

The usage object lacks explicit property definitions. If the usage structure is known (e.g., promptTokens, completionTokens), consider adding them to help API consumers understand the response shape.

app/api/image/generate/route.ts (1)

28-36: Consider adding prompt length validation.

While you validate that prompt exists, there's no maximum length check. Extremely long prompts could cause issues with the AI API or lead to abuse. Consider adding a reasonable length limit.

     if (!prompt) {
       return NextResponse.json(
         { error: "prompt query parameter is required" },
         {
           status: 400,
           headers: getCorsHeaders(),
         },
       );
     }
+
+    if (prompt.length > 4000) {
+      return NextResponse.json(
+        { error: "prompt exceeds maximum length of 4000 characters" },
+        {
+          status: 400,
+          headers: getCorsHeaders(),
+        },
+      );
+    }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 486d0fe and e1d8b97.

⛔ Files ignored due to path filters (3)
  • app/assets/x402_wordmark_dark.png is excluded by !**/*.png
  • app/assets/x402_wordmark_dark.svg is excluded by !**/*.svg
  • app/assets/x402_wordmark_light.svg is excluded by !**/*.svg
📒 Files selected for processing (4)
  • app/api/image/generate/route.ts (1 hunks)
  • app/protected/page.tsx (0 hunks)
  • lib/ai/generateImage.ts (1 hunks)
  • middleware.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • app/protected/page.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/ai/generateImage.ts
🧰 Additional context used
🧬 Code graph analysis (1)
app/api/image/generate/route.ts (1)
lib/networking/getCorsHeaders.ts (1)
  • getCorsHeaders (6-12)
🔇 Additional comments (2)
app/api/image/generate/route.ts (2)

10-15: LGTM!

The OPTIONS handler correctly implements CORS preflight response with appropriate headers.


50-56: Response structure looks correct.

The spread of result aligns with the imageGenerateOutputSchema defined in middleware.ts, which expects the result object at the top level containing images and usage.

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

Successfully merging this pull request may close these issues.

1 participant