The API in Next.js functions perfectly in a local environment but encounters issues in a production

My Next.js application includes a functional API that connects to MongoDB and Prisma. While everything runs smoothly during development, I encounter a 404 error on the API page after deploying the app with Vercel.

Below is the code for app/api/blog/route.ts:

import {db} from "@/lib/db";

import { NextResponse } from "next/server";

export async function GET(){
    try{
        const todos=await db.post.findMany({
            orderBy:{
                date:"desc",
            }

        });
        return NextResponse.json(todos,{status:200})
    }catch(error){
        console.log("[GET TODO]",error)
        return new NextResponse("Internal Server Error",{status:500})
    }

    

}

The code for app/api/blog/[id]/route.ts is as follows:

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

export const GET = async (request:any,{params}:any)=>{
  try{
    const {id}=params;
    const post=await db.post.findUnique({
      where:{
        id
      }
    });
    if(!post){
      return NextResponse.json(
        {message:"Post not found",error: "Post not found"},
        {status:404}
        )
    }
    return NextResponse.json(post)
  }catch(err){
    return NextResponse.json({message:"GET Error",err},{status:500})
  }

}

Details from the package.json file are below:

{
  "name": "portfolio",
  "version": "0.1.0",
  ...

View the appearance at yasith.vercel.app/api/blog

I have checked environment variables and connected MongoDB Atlas to Vercel without success. Feel free to visit the deployed site [here] () I would appreciate any help as this issue prevents me from advancing in fullstack development with Next.js.

Answer №1

Resolved!

The issue stemmed from misuse of mongodb atlas. I mistakenly granted access to all IP addresses, despite it being a security risk.

Answer №2

One solution could be to start a fresh project with the newest version and then transfer your code over. Doing this may resolve any errors you are encountering.

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

The error message "Property 'id' is missing on type 'T'" is indicating the absence of the 'id' property in the

I am currently working on a React component that serves as a table and is designed to handle various types of data. The structure of the component is defined as follows: type SimpleTableProps<T> = { data: Array<T>; ... }; const SimpleTabl ...

Unable to exchange values on the front-end of the next.js app despite the successful operation of the swap function on the back-end

I've built a currency conversion app using next.js and it's running smoothly. However, I'm trying to implement a feature that allows users to easily swap between the From and To currencies. Here is the function code for swapping currencies: ...

Arrange objects in an array according to React

I am looking to implement a filter and sort feature for users to search products based on price range and name, then sort the results by price. Below is my array of products: export const products = [ { name: "Watermelon", price: 3.5, descr ...

The variable being declared at the class level inside a function within the same class is not recognized

Seeking guidance on the code snippet I'm currently studying. I am implementing a TypeScript 1.8.10 compiler along with EM5: module myAmazingModule{ 'use strict'; export interface INavigateService { links: string[], ...

What could be the reason behind the asynchronous/await function not being properly awaited?

Currently, I am working on implementing an Image Upload feature using Cloudinary. The input array can include either base64 coded images or URLs to already uploaded images: [ "https://res.cloudinary.com/\[userName\]/image/upload/v167xxxx4/luxxxfs ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Is there a way to alter the date format for input elements within formGroups using Angular 7?

When the input is of type 'Date', the date format is dd/MM/yyyy. I need to convert the date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calendar). Below is the code snippet. <form [formGroup]="opportunityForm" (ngSubmit ...

How can I resolve the ReferenceError in NextJs which states that Audio is not defined?

Recently, I implemented a Next component that acts as a music player, allowing users to play or stop the audio just like an MP3 player. While the functionality works perfectly fine on my local server – clicking the button triggers the audio play or pause ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

TypeScript's version of Java's enum (or C#'s structure)

I'm facing the challenge of creating an enum in Typescript that mimics the functionality of Java enums. In TypeScript, only integer-based enums like C# are supported, unlike in Java where we can have custom objects with non-integer related properties ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

What could be causing Vercel to struggle with building my Next.js tsx app?

Whenever I run npm run build and npm start on my local machine, it deploys perfectly to localhost. However, when I attempt to deploy the exact same code to Vercel, I encounter the following error: 08:28:16 Failed to compile. 08:28:16 ./pages/index.ts ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

What is the best way to implement a new token/session in next-auth server-side after customizing the signOut method?

Using Next-Auth's credentials provider, the user is signed in by setting their information into a token and then into a session. Cookies are also set. To sign out, I customized the default signOut Method [...nextauth].ts events: { async signOut( ...

Unable to determine all parameters for Modal: (?, ?, ?)

import { Component, Inject } from '@angular/core'; import { NavController, Modal } from 'ionic-angular'; import { PopupPage } from '../../components/modal/modal.page'; @Component({ templateUrl: 'build/pages/spot/spot. ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

Support for dark mode in Svelte with Typescript and TailwindCSS is now available

I'm currently working on a Svelte3 project and I'm struggling to enable DarkMode support with TailwindCSS. According to the documentation, it should be working locally? The project is pretty standard at the moment, with Tailwind, Typescript, and ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...