What causes fs to produce an error when routing to a new page, yet refreshing the page resolves the issue?

Concern:

I have developed a NextJs application with 4 input fields, each connected to a predefined options list read in as a json file within the project. The user can select two fields and then proceed to a search page by clicking a button. From the search page, the user has the option to navigate back home by clicking another button. Initially, the project runs smoothly. However, upon navigating back and forth between the search results page and the home page using Next/Link, an error

TypeError: fs__WEBPACK_IMPORTED_MODULE_17___default.a.readFileSync is not a function
arises, as depicted below:

https://i.stack.imgur.com/vk1an.png

The issue occurs specifically during the getInitialProps() call on the home page. Strangely, this call functions properly when the site is first loaded but encounters problems only when redirecting from one page to another. Interestingly, refreshing the page resolves the error and restores full functionality. It seems that the import of fs is unrecognized upon rerouting, yet functions correctly after being refreshed. Is there a solution to this error besides manually reloading the window?

pages/index.js:

import { Component } from 'react';
import Head from 'next/head';
import FilterBox from '../components/filter-box';
import GreetingBlock from '../components/greeting-block';
import Layout, { siteTitle } from '../components/layout';
import styles from '../styles/Home.module.css';
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import blue from '@material-ui/core/colors/blue';
import orange from '@material-ui/core/colors/orange';
import fs from 'fs';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: blue[500],
    },
    secondary: {
      main: orange[500],
    },
  },
});
class Home extends Component {
  static async getInitialProps() {
    const inputsraw = await fs.readFileSync('./data/inputs.json');
    const inputs = await JSON.parse(inputsraw);
    // console.log('====================')
    return inputs
  }

  constructor(props) {
    super(props);
    this.state = {
      area: '',
      day: '',
      startTime: '',
      endTime: '',
      features: '',
    }
  }
  render() {
    // console.log(this.props);
    return (
      <ThemeProvider theme={theme}>
        <Layout home>
          <Head>
            <title>{siteTitle}</title>
          </Head>
          <GreetingBlock></GreetingBlock>
          <FilterBox inputs={this.props}></FilterBox>
        </Layout>
      </ThemeProvider>
    )
  }
}

export default Home;

pages/search.js:

import Head from 'next/head';
import { Component } from 'react';
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import { getSearchData } from '../lib/search';
import blue from '@material-ui/core/colors/blue';
import orange from '@material-ui/core/colors/orange';
import Layout, { siteTitle } from '../components/layout';
import fs from 'fs'

const theme = createMuiTheme({
  palette: {
    primary: {
      main: blue[500],
    },
    secondary: {
      main: orange[500],
    },
  },
});

export default class Search extends Component {
  static async getInitialProps() {
    try {
      const inputsraw = await fs.readFileSync('./data/inputs.json');
      const inputs = await JSON.parse(inputsraw);
      console.log('====================');
      return inputs
    }
    catch {
      return {}
    }
  }

  constructor(props) {
    super(props);
    console.log(this.props);
  }
  
  render() {
    console.log(this.props.areas);
    return (
        <ThemeProvider theme={theme}>
            <Layout>
                <Head>
                    <title>{siteTitle}</title>
                </Head>
                <h1>HIII</h1>
                <div>{JSON.stringify(this.props.areas)}</div>
            </Layout>
        </ThemeProvider>
      )
    }
}

Versions:

next: 10.1.3

react: 17.0.2

The application is running on WSL2.

Answer №1

When the page is refreshed, it is generated using server-side rendering.

Typical navigation activates client-side rendering.

The fs module relies on Node.js APIs rather than web browser APIs (such as accessing the server's hard drive).


To access JSON data through an API endpoint, utilize the fetch method following the guidelines outlined in the React AJAX and APIs FAQ.

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

How can I achieve the functionality of an image changing when clicked and going back to its original state upon release with the help of HTML

I am facing an issue with styling an element to look like a button and function as a clickable link. My goal is to create a visual effect of a pressed button when it is clicked, while also loading the target page. For reference, here is a (non-working) J ...

What is the best way to apply styling to an image that is contained within the document.write function?

I'm looking to customize the design of this cat image, but I'm struggling to locate where to incorporate the div class. It's likely a basic step, but as a beginner in JavaScript, I'm hoping that someone can assist me. document.write(&ap ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

What is the best way to arrange elements based on the numeric value of a data attribute?

Is there a way to arrange elements with the attribute data-percentage in ascending order, with the lowest value first, using JavaScript or jQuery? HTML: <div class="testWrapper"> <div class="test" data-percentage="30&qu ...

Concealing overflow for text content through CSS styling

I am currently working with an element that contains both an image and text. View the Fiddle here Note: To see the full grid, resize the preview accordingly. The CSS I have written is as follows: .gridster .gs-w .item{ position: relative; wi ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Hovering over the Instagram icon will reveal a stunning visual effect

I am looking to change the appearance of my Instagram icon when hovering over it. I want the background to turn white and the icon to become colored. Here is my code snippet from Footer.js : <a href="https://www.instagram. ...

What is the process for receiving updates while subscribing in ReactReduxContext.Consumer?

I am currently seeking a solution to staying updated on changes to a stored value in the Redux store by subscribing. I have attempted the following method: <ReactReduxContext.Consumer> {({store}) => { console.log('store:& ...

The comparison between importing TypeScript and ES2015 modules

I am currently facing an issue with TypeScript not recognizing the "default export" of react. Previously, in my JavaScript files, I used: import React from 'react'; import ReactDOM from 'react-dom'; However, in TypeScript, I found tha ...

Manipulating Data in TypeScript: Creating a Mutated Copy of a List of Dictionaries

After going through multiple answers, it appears that there might be a logical error. However, I am struggling to find a solution for this issue. In TypeScript/JavaScript, I have two lists of dictionaries. One list is a copy of the other for tracking purp ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

Tips for creating row grouping in React JS

Currently, I am working on a React application and I would like to incorporate grouping similar to what is shown in the image. I have looked into row grouping but it doesn't seem to be exactly what I need. How can I go about implementing this feature? ...

Tips for personalizing the boxshadow in Material UI Card components

I'm having trouble customizing the box shadow for the Material UI card. I attempted to remove the default boxShadow and apply my own style to the cardWrapper I created, but it doesn't seem to be working. How can I add a custom boxShadow without u ...

Recording JavaScript Cookie Visit Counts and Tracking Last Login Dates

I am a beginner in JavaScript and cookies, and I am attempting to create a cookie that can show the number of times someone has visited a website, the date of their last visit, and the expiration date of the cookie. Initially, I tried modifying code from ...

Conceal form after submission - Django 1.6

I'm currently working on a Django 1.6 project where I have this form: <form action="/proyecto/" method="POST" id="myform"> {% csrf_token %} <table> <span class="Separador_Modulo">& ...

iterating over a large multidimensional array in JavaScript

I am facing a challenge with handling a large JSON dataset (around 20k+ entries, totaling over 2mb) that I need to display on my web pages. Currently, I fetch this data using AJAX and parse it using JSON.parse in JavaScript, resulting in a complex multidi ...

Accessing variables from an external script in jsdom

Here is a simple example of jsdom code using the script parameter. Despite my best efforts to reference external JS files, I keep running into this issue: ReferenceError: exVar is not defined Does anyone know what might be causing this problem and how ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Is it possible to dynamically insert one module into another module?

Let's say I have 2 modules in two separate files: The first one is for everyone, let's call it myApp: var myApp = angular.module('myApp', ['dependency.one', 'dependency.one']); In another file named admin.js, I ha ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...