Next.js API routes encountering 404 error

I am encountering an issue with calling my route API (404) in my new nextjs project.

The route API can be found at src/app/api/speed.js

Within my page src/app/page.tsx, I have the following code snippet:

fetch("api/speed").then(res=>res.json).then(data=>alert(data.message))

Despite this, I consistently receive a 404 error on GET http://localhost:3000/api/speed when checking the network devtools tab.

The content of src/app/api/speed.js is as follows:

export default function handler (_req,res) {
  res.status(200).json({ message: "hey" })
}

In src/app/page.tsx:

'use clients;
export default function Home() {
  function handleClick() {
    fetch("api/speed").then(res=>res.json.then(({message})=>alert(message))
  }
 
  return (
    <><main><div onClick={handleClick}>HEY</div></main><>
  )
}

Note: The API route functions correctly if moved to src/app/api/speed/route.js. However, based on the documentation example of pages/api/hello.js, it should work in the original location.

Note 2: In addition to relocating the API route, I also had to make adjustments to the code. The provided example in the official documentation was not functional (possibly deprecated). Here is the updated code:

import {NextResponse} from "next/server";
export async function GET(req) {
  return NextResponse.json({message: "hey"})
}

What could be causing this issue?

Answer №1

To include an API router within the app router, you will need to create a file called route.js/ts and export the handler functions using the method name. Here is an example:

src/app/api/speed/route.js
export const GET = () => {
    return Response.json({ data: "hello world" })
}

Once this is set up, you can fetch data in the same way as before!

fetch("api/speed")
    .then(res => res.json())
    .then(({ data }) => console.log(data))

For further information, refer to the documentation

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

What is the reason for TS expressing dissatisfaction about the use of a type instead of a type entry being provided

Below is a snippet of code for a Vue3 component that takes in an Array of Objects as a prop: <script lang="ts"> interface CorveesI { What: string, Who: string, Debit: number } export default { name: 'Corvees', props: { ...

Having trouble with VS Code on my Linux system - npm error popping up?

protons@protons-HP-EliteBook-840-G3:~/Desktop/NH_Facility_Portal_V0$ sudo npm install [sudo] password for protons: npm notice npm notice New minor version of npm available! 8.12.1 -> 8.13.2 npm notice Changelog: https://github.com/npm/cli/releases/tag ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

The call to react.cloneElement does not match any overloads

I'm encountering a typescript error in my React code when using React.cloneElement with the first parameter "children", and I am unsure of how to resolve it. As a newcomer to typescript, I believe that the type definitions in index.d.ts for cloneElem ...

Creating a generic array type in TypeScript that includes objects with every key of a specified interface

I am working with an interface called Item interface Item { location: string; description: string; } Additionally, I have a generic Field interface interface Field<T extends object> { name: keyof T; label: string; } I want to create an Arra ...

Exploring the correct implementation of Dynamic Routes in Next.js 13 is essential for mastering the framework

I need the /profile and /profile/[id] URLs to be directed to a single page within my project. Nextjs offers the profile/[... id]/page.tsx route, but I would prefer not to have too many parameters. At this point, I am unsure of how to create a route that ac ...

Employ a class decorator to modify methods within a subclass

Is there a way to utilize class decorators in order to modify the methods of subclasses for the decorated class? This particular example showcases how to alter the class's own methods, but does not extend to its subclasses: export function guardAllNo ...

Having trouble with Prisma nextauth after changing the user model name from User to XYZUser

In my current project, we are using Nextjs, Next-auth, Prisma adapter, and Supabase for user authentication. Everything was working smoothly when the database model was named 'User'. However, after changing the model name to 'WebUser', ...

Error: Unrecognized action type in Vuex

I've been encountering some major issues with vuex lately. For some reason, getters, actions, and mutations are not being recognized. In the code snippet below, although fetchFacilities is working fine, addFacility is throwing an error: [vuex] unknown ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Error in nextjs: The function createServer is undefined

I came across this tutorial that I'm attempting to follow: I've hit a roadblock at step 3, where the server is defined as shown below: import { createServer } from "@graphql-yoga/node"; import { join } from "path"; import { r ...

Encountering an error with Next-Slicezone module integration with Prismic.io: "module parse failed"

I'm feeling lost and frustrated as I struggle to figure out what's going wrong. The documentation for slicezone in nextjs is not very clear, and the Prismic Community board hasn't been very helpful either. Can someone please assist me with t ...

How to create a collapse feature that allows only one item to be open at a time in Angular

I developed an angular app with a collapse feature, but I noticed that multiple collapses can be open at once. I am utilizing Ng-Bootstrap collapse for this functionality. Below is the code snippet from the TS file: public isCollapsed = true; And here is ...

What is the best way to include body parameters in a Next.js rewrite?

Consider the following POST request: const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: JSON.stringify({ grant_type: "password&quo ...

The data type '{ [key: string]: number; }' cannot be assigned to type 'T'

I’m working with a complex TypeScript type and trying to manage it within a function. Here’s what I have: type T = { a: number } | { b: number } function func(k: 'a' | 'b', v: number) { // error message below const t: T = { ...

typescript, generate a new type by merging option values

In typescript I am faced with a challenge. I have a type called A: interface A { a1: string; a2: int; } As well as another type called B: interface B { b1: number } Now, my goal is to create a new type: interface AB { a1?: string; a2? ...

Implementing error wrapper in typescript to handle failing promises with n retries

I have a wrapper function that calls an async function: function fetchAPI(arg1: number, arg2: number, arg3: string) { return new Promise((resolve, reject) => { try { myFetchFunction(arg1, arg2, arg3).then((r: any) => { if (!r) { ...

Is it possible to use custom hooks in GetStaticProps() within Next.js?

Is there a way to utilize the custom hook within the getStaticProps() function? We are fetching data from the Contentful CMS using the Delivery API, and having custom hooks for specific data retrieval would be more convenient. When attempting to call useH ...

What steps should be taken in order to resolve the error message "Type is missing an index signature"?

Is there a solution to this type error? The argument of type 'Query' is causing an issue as it cannot be assigned to the parameter of type 'Input'. This is due to the absence of an index signature in type 'Query'.(2345) In ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...