Skip to content

Enable fetch API requests with proper URL for local development and production deployment #29

@plpxsk

Description

@plpxsk

if you want to add fetch API requests or similar, you have to be careful with URLs.

In your app, you may have something like this in route.ts:

export async function POST(req: Request) {
    const requestData = await req.json();

    const response = await fetch('http://localhost:8000/api/py/chat', {
      ...
      });

The above works on local, but naturally, not when deployed to production.

It seems that relative URLs won't work.

Therefore, use this instead:

    const BASE_URL =
	process.env.NEXT_PUBLIC_VERCEL_ENV == null ||
	process.env.NEXT_PUBLIC_VERCEL_ENV === "development"
	? "http://localhost:8000"
	: process.env.NEXT_PUBLIC_VERCEL_ENV === "preview"
	? `https://${process.env.NEXT_PUBLIC_VERCEL_URL}`
	: `https://${process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL}`;

    const response = await fetch(`${BASE_URL}/api/py/chat`, {
      ...
      });

Per vercel/next.js#16429 (comment)

EDIT: clarify this is in route.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions