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 could be causing the malfunction of getter/setter in a Vue TypeScript class component?

Recently delving into the world of vue.js, I find myself puzzled by the unexpected behavior of the code snippet below: <template> <page-layout> <h1>Hello, Invoicer here</h1> <form class="invoicer-form"> ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Creating aesthetically pleasing class names using SASS and CSS modules

I'm in the midst of working on a Next.js project and experimenting with SCSS/SASS for my styling needs. I'm currently grappling with how to streamline the process of applying class names. Here's the issue at hand: Within one of my componen ...

Establishing a MongoDB connection only once in a Next.js application

I'm new to Next.js and have a question about database connections. In Express projects, we typically establish the connection in the main file (app.js), but it seems like in Next.js, the database connection needs to be inside the API file. Will this r ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

Issue with extending mongoose.Document properly in NodeJS and TypeScript using a custom interface with mongoose

I recently started learning Typescript and tried to follow this guide to help me along: After following the guide, I implemented the relevant code snippets as shown below: import { Document } from "mongoose"; import { IUser } from "../interfaces/user"; ...

The Vanilla JS script in Next.js fails to execute upon deployment

Currently developing a simple static site with Next.js. The lone vanilla JS script in use is for managing a mobile menu - enabling toggling and adding a specific class to disable scrolling on the body: if (process.browser) { document.addEventListener(&ap ...

Is there a way to send an array of objects using axios-http?

Currently, I am utilizing react-dropzone for uploading mp3 files and a metadata npm to extract all the file contents. However, upon sending it to axios.post(), an error is encountered stating "Body Exceeded 1mb limit" Here is the snippet where the new dat ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

The function User.find does not exist and it is not possible to replace the `users` model after it has

Currently, I am experimenting with using mongoose, mongoDB, next, and express in a test project. Despite referencing solutions like Cannot overwrite model once compiled Mongoose and others, I am encountering issues unique to my situation. Upon initializat ...

Issue: Server Components can only communicate with Client Components by passing plain objects or some built-in types. Unsupported data structures include classes and objects with null prototypes

I have been working on a react application that is supposed to fetch data from an API and display the name of a material obtained from the API. The JSON data appears correctly when I call the API in the browser. However, upon reloading my frontend page, I ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...