When users click on the next/link, it is triggering a problem within the getInitialProps function

Currently, I am attempting to include a link that will direct users to the create page. However, when I tried clicking on the link, I encountered the following error:

TypeError: Cannot read properties of undefined (reading 'cookies')

The code for the link is as follows:

<Link href={link}>Add New Employee</Link>

This snippet of code is found in getInitialProps within _app.tsx:

MyApp.getInitialProps = async (context: any) => {
    const {req, res, pathname} = context.ctx;
    const {language, auth_key} = req.cookies;

    return {
        lang: language ?? 'ar',
        token: auth_key ?? null,
    }
};

Answer №1

To ensure your code runs seamlessly on both the server and client sides, it is essential to incorporate isomorphic code within the MyApp.getInitialProps function.

Referencing the documentation on getInitialProps:

During the initial page load, getInitialProps will execute exclusively on the server. Subsequently, when navigating to a different route using the next/link component or next/router, getInitialProps will be triggered on the client side. However, if getInitialProps is utilized in a custom _app.js file, and the destination page contains getServerSideProps, then getInitialProps will run on the server.


If you encounter an error, consider implementing the following solution. The code checks for the existence of req before accessing req.cookies. If found, the cookies are retrieved from the document instead.

// Retrieve cookie from `document` on the client-side
const getCookie = (name) => {
    const match = document.cookie?.match(new RegExp(`(^| )${name}=([^;]+)`));
    return match?.[2];
};

MyApp.getInitialProps = async (context) => {
    const { req } = context.ctx;
    const language = req ? req.cookies.language : getCookie('language');
    const auth_key = req ? req.cookies.auth_key : getCookie('auth_key');

    return {
        lang: language ?? 'en',
        token: auth_key ?? null,
    }
};

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

Shut down the pop-up in Chrome before the DOM finishes loading

Utilizing the most recent iteration of the selenium web driver along with the Google Chrome browser, I am encountering an issue in my application. Following the click on the login button, a popup appears while the DOM is still loading. view image I simpl ...

What could be causing these strange white lines to show up on my AFrame meshes?

When I import a GLB scene with baked textures into A-Frame using THREE.js, I am experiencing an issue where white lines appear on my objects (pictured below). The walls are grouped meshes which may explain the lines appearing there, but I am puzzled as to ...

ngSanitize continues to present plain text rather than rendering HTML code

When working with AngularJS scope, I encountered the need to display certain items as HTML. After some research, I realized that integrating ngSanitize was necessary for this functionality. Here is how I implemented it in my app: <script src="Scripts/a ...

Establishing a connection to an active process within Winappdriver with the utilization of JavaScript

As someone who is fairly new to working with JS and WinAppDriver, I am currently facing a challenge with testing a Windows-based "Click Once" application built on .Net. To launch this application, I have to navigate to a website through Internet Explorer a ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...

Each time the web animation is utilized, it gets faster and faster

As part of an assignment, I am working on creating an interactive book that can be controlled by the arrow keys and smoothly comes to a stop when no key is being pressed. However, I have noticed that with each arrow key press, the animation speeds up. Bel ...

The HTML button triggers a function to execute on a different webpage when clicked

I'm facing a straightforward issue that I can't seem to figure out due to my limited experience with Angular and web development. The problem revolves around two components, namely home and dashboard. In the home.component.html file, there's ...

JS : Removing duplicate elements from an array and replacing them with updated values

I have an array that looks like this: let arr = ['11','44','66','88','77','00','66','11','66'] Within this array, there are duplicate elements: '11' at po ...

Check if an element possesses a specific property and corresponding value in JavaScript

I was looking to determine if an object has a specific property with a certain value, and wanted to search for it within an array of objects. var test = [{name : "joey", age: 15}, {name: "hell", age: 12}] After testing the code snippet below, I realized ...

Leveraging a service variable in Angular

Is there a way to access data shared in a service within a directive? Let's say we have a directive called resultsDirective, and a service named dataService. How can we retrieve a variable from the service within the directive? angular.module("someMo ...

Utilize Jquery to insert the text into the input or textarea field

<div class="ctrlHolder"> <label for="" id="name.label">Name</label> <input name="name" id="name" type="text" class="textInput small" /> <p class="formHint">Please enter the name of the item you are submitting</p> </di ...

Creating dynamic images with animated text using PHP

How can I add a personal touch to my website banners for visitors? 1) Currently, only the first frame of GIF images is being displayed in the animated banners 2) I am looking to incorporate a text field where users can input their desired text. Upon form ...

Is there a way to create a JavaScript script that automatically updates a webpage for all users simultaneously?

I have developed a web application that enables users to modify content using JavaScript. Currently, these changes are only visible on the local browser and do not involve AJAX. However, I am wondering how I can ensure that these DOM alterations are refle ...

Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated. The issue ...

Experiencing a 404 error after attempting to access an endpoint following a successful MSAL Azure AD

Incorporating the UserAgentApplication.loginPopup function to authenticate users on our Azure AD has been a challenge as we transition from an ASP.NET MVC application to a Vue.js front end and ASP.NET 'API' backend. The goal is to pass the access ...

KnockoutJS is not recognizing containerless if binding functionality

I was recently faced with the task of displaying a specific property only if it is defined. If the property is not defined, I needed to show a DIV element containing some instructions. Despite my efforts using $root and the bind property, I couldn't ...

"Why does the form.submit() function fail in IE9 when the form is in an iframe and the user is coming from Gmail

I have recently developed a function within my CodeIgniter framework that allows me to send emails with a backlink to my site. The link directs users to a page on my website that includes an iframe. Within this iframe, I have implemented a file input form ...

Can we activate or attach a jQuery UI event?

Similar Question: jQuery AutoComplete Trigger Change Event After successfully implementing the jQuery UI Autocomplete widget using version 1.9, I am curious to know if it is possible to trigger or bind a jQuery UI event. For example, can the jQuery UI ...

Is the array State not setting properly in React Native?

I apologize for the strange request, but I need help with a validation method for form inputs within a modal. Currently, I am checking each this.state.variable and pushing them to an aux array, which is then supposed to be set to the original fieldErrors ...

Troubleshooting: Issues with MongoDB Aggregation not reflecting updates in my collection

Currently, I am attempting to execute an aggregation query in Mongo utilizing their nodejs driver. The query involves aggregating some fields, calculating averages, and other operations. I constructed the aggregation in Mongo Cloud and then exported it to ...