NextJS 14 site working in development but not in vercel

38 Views Asked by At

I have a page(server component) that fetches some data from a route handler(/api/v1/bookings/get) in my app.

Running my site with next dev --turbo works fine and does not give any errors but when deploying to vercel, I get the error Application error: a server-side exception has occurred (see the server logs for more information)

Looking at my logs, I see a warning that says that the route /api/v1/bookings/get was not found, which is weird because it seems to have been build when deploying the project as per the deployment summary on vercel. Deployment summary

After the 404 I see a error that tells my front end was unable to parse the response returned(which should be in JSON but is probably in HTML since the API route was not found) errors list
error closeup


For my route handler, it is a simple file that gets all the 'rides' for a specific user(determined by their email). It's code is:

import { auth, currentUser } from "@clerk/nextjs/server";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function GET() {
  const user = await currentUser();
  auth().protect();

  try {
    const bookings = await prisma.ride.findMany({
      where: {
        rider: {
          email: user?.primaryEmailAddress?.emailAddress,
        }
      }
    });

    return new Response(JSON.stringify({bookings}), {
      status: 200,
    });
  } catch (error) {
    console.log(error);

    return new Response(JSON.stringify(error), {
      status: 500,
    });
  }
}

The front end looks like:

import booking from "@/types/bookings";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardTitle,
} from "../ui/card";
import Link from "next/link";
import { Button } from "../ui/button";

export default async function Bookings() {
  const res = await fetch(process.env.BASE_URL + "/api/v1/bookings/get", {
    next: {
      revalidate: 60,
    },
  });
  const response: { bookings: booking[] } = await res.json();
  const bookings = response.bookings;
  return (
    <div className="p-4 m-4">
      <h1 className="text-3xl font-bold">Previous bookings</h1>
      <div className="grid grid-cols-2 grid-rows-5 gap-2">
        {bookings.length > 0 ? (
          bookings.map((booking) => (
            <Card key={booking.id}>
              <CardTitle>{booking.name}</CardTitle>
              <CardDescription>
                {new Date(booking.created).toLocaleDateString()}
              </CardDescription>
              <CardContent>
                A {booking.duration} hour trip with {booking.people} people and{" "}
                {booking.driver && booking.driver.name} as driver.
              </CardContent>
              <CardFooter>
                From {booking.startLocation && booking.startLocation.city} to{" "}
                {booking.endLocation && booking.endLocation.city}
              </CardFooter>
            </Card>
          ))
        ) : (
          <div>
            <p>You don&apos;t have any bookings yet. Make your first!</p>
            <Link href={"/dashboard/book"}>
              <Button variant={"secondary"}>Book a ride.</Button>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}

I manually set the base URL variable in my .env file.

Searching for a fix on Google, I saw a few people suggesting purging the cache(on Vercel's side), which I tried but didn't work, I also redeployed afterwards.

File structure:
file structure

Any idea how I can fix this?

1

There are 1 best solutions below

1
adampweb On

The issue is caused by a malformed request URL. To run the GET function you must be request with GET method.

Example:

const getBookings = async () => {

try {
  const res = await fetch('http://<your-site-host>/api/v1/bookings',{
    method: 'GET',
    headers: {
      'content-type': 'application/json'
    }
  })
  if(res?.ok){
    console.log(res)
  }else{
    console.log("Oops! Something is wrong.")
  }
} catch (error) {
    console.log(error)
}

}

Your logs contains a item with a GET method request to /api/v1/bookings/get but to correct path is /api/v1/bookings

For more examples please look for official docs.