Vercel deployment encountered an AxiosError with a status code of 404

I am currently working on an API route called app/api/posts/route.ts, which is responsible for fetching all posts from my database using Prisma ORM. In the localhost environment, the database is hosted on my local PostgreSQL server. However, in production, the database is located on render.com. To fetch the data, I utilize axios within a function defined in app/page.tsx. Here is the code snippet:

import Card from "@/components/Card";
import axios from "axios";

const getPosts = async () => {
  const url =
    process.env.NODE_ENV === "development"
      ? "http://localhost:3000/api/posts"
      : "https://dropconnect.vercel.app/api/posts";
  const res = await axios.get(url);
  const data = await res.data;

  return data;
};

export default async function Home() {
  const posts = await getPosts();
  return (
    <div>
      {posts.length === 0 ? (
        <div>
          <p>No Posts have been made yet</p>
        </div>
      ) : (
        <div>
          {posts.map((post: any) => (
            <div key={post.id}>
              <Card
                id={post.id}
                title={post.title}
                content={post.content}
                comments={post.comments}
                noComments={post.noComments}
                noLikes={post.noLikes}
                name={post.author.name}
                image={post.author.image}
              />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

The code for my /app/api/posts/route.ts is as follows:

import { prisma } from "@/lib/database";
import { NextResponse } from "next/server";

export async function GET(req: Request) {
  const allPosts = await prisma.post.findMany({
    include: {
      comments: true,
      author: {
        select: {
          name: true,
          image: true,
        },
      },
    },
  });
  return NextResponse.json(allPosts);
}

Additionally, here is my schema.prisma:

// Your unique Prisma schema file,
// for more information visit the official docs at: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Post {
  // Model definition for Post table
}

...

// Additional model definitions like Comment, Account, User, etc.

...

Currently, everything works smoothly when running in the localhost environment: https://i.stack.imgur.com/RCq9T.png

However, upon deploying to GitHub, Vercel encounters an AxiosError with the following details:


... (error log details here)

If you have insights or suggestions on this issue, your help would be greatly appreciated.

Answer №1

An issue arises because the localhost is not accessible on vercel and you are also using a custom domain which is undefined since the domain connection occurs at the final stage of deployment. However, your code includes SSG and a server component.

To resolve this error, integrate this code directly into your server component...

const allPosts = await prisma.post.findMany({
    include: {
      comments: true,
      author: {
        select: {
          name: true,
          image: true,
        },
      },
    }
})

Answer №2

Here's the solution I came up with:

I decided to simplify things by starting fresh in app/page.tsx. I created a basic component with just an h1 tag, pushed that code to Vercel, and it deployed successfully without any errors. Next, I reintroduced the original code from app/page.tsx, which I had initially shared in my question, and pushed it to GitHub. Again, the deployment went smoothly without any hiccups.

My theory is that during the first deployment, Vercel and Next were verifying the code and attempting the Axios GET request, but failed because the /app/api/posts/route.tsx file hadn't been generated yet by the npm build command. By following the steps I took, the route was established in the first deployment, allowing for a successful API call in the second deployment as Axios no longer encountered any issues.

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

Tips for preventing CORS and SSL issues when using localhost

Attempting to log in with Google on my Svelte app involves sending a request to an Express server. However, I encounter different errors on different browsers. On Firefox, I receive a Cross-Origin Request Blocked: The Same Origin Policy disallows reading t ...

Using Angular2's component templateUrl with a npm package

Seeking advice on the best way to reference templateUrl in a commonly used npm module. I want to avoid including node_modules in the path, as the directory could potentially be renamed. Is there an alternative method that still works effectively? For exam ...

Is it considered best practice to pass an argument that represents an injectable service?

Is it a good practice to pass an argument that is an injectable service to a function? Hello everyone, I have been doing some research but have not found a definitive answer to the question above yet. I am currently working with Angular and came across so ...

Executing server side code using client data in next.jsIn next.js, executing server side code with data

Is there a way to extract metadata from a URL that is provided by the user in my Next.js application? To achieve this, I am utilizing a tool called metadata-scraper. However, upon submission of the form by the user, my application encounters an error: ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Sentry is causing issues with the build of my Next.js application

After integrating Sentry into my Next.js project, I have encountered an error that is preventing the application from building. The same error also occurs at runtime, but what confuses me is why it's affecting the build process. Is there a way to conf ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

Using TypeScript to Return a Derived Class as a Method's Return Type

I'm currently facing a challenge with an abstract class in typescript that includes a method to provide a callback for later use. The issue lies in the return type of the method, as it is set to the class itself, preventing me from using fluent style ...

Searching Firestore database using parameters in the URL

I am striving to retrieve plants that have a folderId with a value based on the parameters from useRouter. Although there are no errors, no data is being returned, and there are indeed plants with folderId in the "PlantsData" collection. Here is the code ...

The data type returned by a method is determined by the optional parameter specified in the

I have a situation where I need to create a class with a constructor: class Sample<T> { constructor(private item: T, private list?: T[]) {} } and now I want to add a method called some that should return: Promise<T> if the parameter list ...

I am facing an issue with my getServerSideProps function being undefined in my Next.js application, despite using a class component. Can anyone help me troub

Hey there, I'm currently facing an issue with retrieving props using getServerSideProps. I've tried various solutions but haven't been able to make it display properly. Below is the code snippet: import React, { Component } from 'react& ...

Ensure that all files with the extension ".ts" take precedence and are imported

I am facing an issue with my component as I have two files associated with it: app/components/SomeButton.ts app/components/SomeButton.tsx The .ts file contains most of the logic and code, while the .tsx file extends the .ts and only contains the ren ...

Having trouble deleting JavaScript object properties within a loop?

Struggling to comprehend the behavior of this particular piece of javascript code. const devices = searchResult.results.forEach(device => { const temp = Object.keys(device.fields); for(var property in temp) { if(device.fields.hasOwnPro ...

What is the method for launching Chrome synchronously in Selenium WebDriver using createSession()?

After executing the code below using Selenium WebDriver to launch a Chrome browser: import { Driver } from 'selenium-webdriver/chrome'; Driver.createSession(); console.log("I've launched!"); I'm encountering an issue where "I've ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

Error message encountered in Next.js when trying to import 'SWRConfig' from 'swr': ClerkProvider Error. The import is not successful as 'SWRConfig' is not exported from 'swr

I recently started working on a new Next.js project and integrated Clerk into it. I set up the env.local and middleware.ts files before wrapping the HTML div with ClerkProvider. However, when attempting to run the project locally, I encountered the followi ...

Why is the source alignment different when using Next.js compared to WordPress?

As a newcomer to NextJS, I am eager to learn more about it in order to develop websites that are easily discoverable by Google's search engine algorithms and have strong SEO performance. Wordpress is renowned for its SEO capabilities as it neatly outp ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

The element is assumed to have an 'any' type due to the index expression not being of type 'number'. - Error in Index Signature

I've recently started using TypeScript and encountered the following issue: Element implicitly has an 'any' type because index expression is not of type 'number' This error message appears on this line --> const { status, msg ...

The robots.txt of Websiteplanet does not specify a sitemap URL

This is how my robots.txt file is set up: User-Agent: * Disallow: /info/privacy Disallow: /info/cookies Allow: / Allow : /search/Jaén Allow : /search/Tarragona Allow : /search/Rioja Sitemap: https://www.alquileres.xyz/sitemap.xml However, when I verify t ...