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

Configuring Next.js with Next-Auth, Apollo, and GraphQL

Seeking advice on navigating a next.js front end using Apollo and GraphQL to connect with a PostgreSQL database. Initially, I separated the front and back ends assuming it would be beneficial, but now facing some tradeoffs. Next.js and NextAuth.js seem opt ...

Passing both the object and its attributes simultaneously for reflect-metadata in TypeScript is a feature that closely resembles functionality found

Instead of using DataAnnotation in C# to add meta attributes on properties, I am seeking a similar functionality in TypeScript for a ldap model class. The goal is to have decorators that can set the LDAP attribute used in the LDAP directory internally. ex ...

Creating a return type in TypeScript for a React Higher Order Component that is compatible with a

Currently utilizing React Native paired with TypeScript. Developed a HOC that functions as a decorator to add a badge to components: import React, { Component, ComponentClass, ReactNode } from "react"; import { Badge, BadgeProps } from "../Badge"; functi ...

Tips for concealing XHR Requests within a react-based single page application

Is there a way to hide the endpoint visible in Chrome's devtools under the network tab when data is fetched in React? Can server-side rendering solve this issue? ...

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...

Creating a dynamic CSS height for a div in Angular CLI V12 with variables

Exploring Angular development is a new venture for me, and I could use some guidance on how to achieve a variable CSS height in Angular CLI V12. Let me simplify my query by presenting it as follows: I have three boxes displayed below. Visual representatio ...

Exploring the world of shaders through the lens of Typescript and React three fiber

Looking to implement shaders in React-three-fiber using Typescript. Shader file: import { ShaderMaterial } from "three" import { extend } from "react-three-fiber" class CustomMaterial extends ShaderMaterial { constructor() { supe ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...

What is the best way to incorporate the TUI image editor for Javascript into my Angular application?

Issue - I'm facing a challenge with my Angular application as I want to integrate Toast UI image editor. However, I am unsure about how to properly add the imports to app.module.ts in order to utilize it. Despite following the npm installation instru ...

Can variables be declared for file paths within the HTML code in a TypeScript file?

We utilize the Vaadin designer to create the frontend of our project. Within the .ts files, we have images where we aim to establish variables for the file paths. Currently, the setup looks like this: <img src="../../themes/light/img/example.jpg&q ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

Solving the error message "window is not defined" in Nextjs

Hey, I'm attempting to create a component similar to [this tutorial][1] in my NextJS app but I'm running into an error ReferenceError: window is not defined //Navbar.js import styles from "../styles/Navbar.module.css"; export default fu ...

How can we update API requests based on dropdown selection changes in Next.js?

Currently, I am working on a calendar project using Next.js. The calendar needs to change based on the selected country and year, for which I am utilizing a holidays API. The API URL includes parameters for country and year (https://localhost:5001//holiday ...

NextJS app router paired with Auth0 UserProvider

I have initiated the process of migrating my company's entire React application to NextJS version 13.4.8 using the app/ directory structure. Our authentication provider is Auth0, and we do not plan on implementing NextAuth. Based on the documentation ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Is there a way to retrieve the type of a generic class in JavaScript?

class Alpha { static construct<T extends typeof Alpha>(this: T): InstanceType<T> { const v = new Alpha(); return v as InstanceType<T>; } } class Beta extends Alpha {} const x = Alpha.construct(); // generates Alpha const y = ...

Any idea how to resolve this typescript typing issue: "The argument, either a string or number, cannot be assigned to the parameter of type 'SetStateAction<string>'"?

Just recently delving into TypeScript, I've encountered a persistent typing problem that has proven challenging to resolve despite numerous attempts. The error message causing me trouble reads as follows: Argument of type 'string | number' ...

Error: Attempting to access properties of an undefined value

I am facing an issue with my project that is built on NextJs for the frontend and Strapi CMS for the backend. I have a collection type named blogs to display blogs on my website. Despite adding all necessary fields for the blog, I encounter the following e ...

Error in Next.js: react-dom.development.js?ac89:14906 - Hook call is invalid. Hooks should only be used within a function component's body

Here is the code snippet I am working with: <div onClick={(e) => handleClick()}>Join Us</div> This is the handleClick function in my code: const handleClick = () => { console.log(Lang.getLocale()) }; And this is the Lang class metho ...

Utilize a visual representation as the icon within an IconButton component in ChakraUI

Is there a way to incorporate a .png file into the IconButton in Chakra UI? I've tried setting icon="/image.png and src="/image.png, but it doesn't seem to work. How can I successfully pass an image as the icon for the IconButton compon ...