Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.txt. However, when trying to read the file, it seems to break the functionality. Interestingly, when the code is hardcoded with msg, it works without any issues!

app/api/myapi.js

var fs = require('fs');
export default function handler(req, res) {
  var msg = fs.readFileSync("mydata.txt")
  if(req.body=="Me"){ res.status(200).json({ message: `Logged in` }) }
  else{ res.status(200).json({ message: `Error ${msg}` })  } 
}

Within the index.html file, I attempt to fetch the response and alert it. The content of mydata.txt is currently set as "Not logged in". (mydata.txt resides in the app/api directory, although I also attempted moving it to the root directory.)

The errors encountered are always:

POST 404 (Not Found) VM155:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input

I experimented with relocating the mydata.txt file to various directories. Surprisingly, when msg was hardcoded, everything worked perfectly.

Answer №1

It appears there may be some confusion between the app router (introduced in NextJS 13) and the page router. These two routers require different styling approaches, as even the official NextJS documentation has separated the instructions based on the type of router being used.

For those utilizing page router:

  • The parent folder should be named page
  • You can simply modify your existing file by changing the path to /pages/api/myapi.js

If you're opting for the app router:

  • The parent folder needs to be named app
  • Your file should be named route.js. In your scenario, the path should be set to /app/api/myapi/route.js
  • Handler functions must be labeled with HTTP verbs such as GET, POST, etc., each one exported individually.
  • Keep in mind that the parameters within the handler functions differ from standard express requests and responses. In TypeScript, the handlers should accept an object with a type of NextRequest, rather than the typical express.Request.

If you wish to proceed with the app router, it will be necessary to make adjustments to your code accordingly.

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

jQuery width property does not seem to be functional on menus that do not contain any dropdown

I am currently working on creating a menu that displays arrows underneath the items when hovered over or when the .active class is added to the menu. Everything is working fine, except for the fact that it only works on menus with drop-downs and the child ...

Trigger an action in the clean-up function of useEffect

I am facing an issue with a form component in a Material UI <Tab /> where users can update their address information. The data is fetched from the API using redux-thunk, and the form fields are pre-filled with server data before the update occurs. T ...

Using an image for the axis in Wijmo BarGraph

I am currently working with Wijmo barcharts and attempting to create a graph that uses images instead of labels on the x-axis. The code I have at the moment displays the image source as a string rather than displaying the actual image. Does anyone know ho ...

Event handler or callback function in Socialite.js

Exploring the capabilities of Socialite.js for the first time has been quite intriguing. This JavaScript plugin allows loading social media plugins after page load, adding an interesting dynamic to website interactivity. However, I am faced with the challe ...

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

Select a background using the Konvas.js library by clicking on a CSS class

I am attempting to use Konvas.js to change the background when clicking on an image with the imgback class: Link to Code I want to avoid assigning an id to each individual image Here is the code snippet: Jquery: $('.back').click(function(){ ...

Ideas and Recommendations for Building a Laravel and Vue.js Hybrid Structure for MPA/SPA Applications

Consider the innovative approach I've been pondering - a combination of MPA and SPA, where each page functions as a Single Page Application, yet still reloads when navigating from one page to another (e.g. index.blade.php to posts.blade.php) like a tr ...

Creating a smooth fading effect for an element within a react component

I am currently working on implementing a fade out warning/error message (styled with Bootstrap) in a React component, however, I am encountering some challenges with the timing of the fade-out effect. Up to this point, the fade out effect is functioning c ...

IIFE and the Twitter share button are a powerful duo

As I experiment with this quick creation of mine, two questions have arisen. The first one is, how can I encapsulate all the JS code within an IIFE without breaking it? The second question is about finishing the twitter button to enable sharing the act ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Organizing HTML elements based on their class names, especially when an element has multiple classes assigned

Hey there, I've been working on an artist page that showcases multiple artists, each with a portfolio image and some detailed information. My goal is to have buttons at the top of the page that, upon clicking, will sort the artists displayed. To achi ...

In some cases, the Ajax reading or fetching variable may have difficulty retrieving the precise variable when working with CodeIgn

I've encountered a puzzling issue with my ajax code, or perhaps it's related to ajax itself. My code retrieves a value from a label and combines it with fresh data from the database. Strangely enough, every time I refresh the page, the output var ...

Executing javascript function using setInterval

I'm trying to make a JavaScript function that rotates between Divs every 1500ms (1.5s) This is what my script currently looks like: <?php $rowCount = 3; $prefix = 'ITS_'; ?> var step = 1; var stepmax = <?php echo $rowCount; ? ...

What is the best way to create a nested item in the database?

Encountering various difficulties while attempting to create a new user with a nested related table in my database setup: model User { id Int @id @default(autoincrement()) username String @unique ...

``What is the mechanism behind callbacks in AngularJS when making a call to a REST service?

Currently, I am diving into the world of AngularJS and REST. The code snippet that I'm analyzing has the term callback repeatedly used in an authentication function. I'm curious to know if "callback" is a JavaScript or Angular keyword, or simply ...

Exploring the capabilities of NodeJS together with the fetch function of Backbone

I have a code snippet for the front-end using fetch: var MyModel = Backbone.Model.extend(); var MyCollection = Backbone.Collection.extend({ url: '/questions', model: MyModel }); var coll = new MyCollection(); ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

Is there a way to access window.location.hash through a Next.js application?

Whenever I use useEffect with window.location.hash, it consistently returns '0' incorrectly. This issue seems to be related to Server-Side Rendering. I am looking for a dependable way to extract the hash from the URL in my project. What would be ...

Executing synchronous animations in Jquery with callback logic

My jQuery plugins often rely on user-defined callbacks, like in the example below: (function($) { $.fn.myplugin = function(options) { var s = $.extend({}, options), $this = $(this); if (typeof s['initCallback'] = ...