Error: Vercel deployment of Next.Js app fails due to undefined localStorage

Encountering the issue

ReferenceError: localStorage is not defined
when attempting to deploy my Next.JS app on Vercel.

const NewReserve: React.FC = () => {
  const setValue = (key: string, value: string) => {
    return localStorage.setItem(key, value);
  };

  const getValue = (key: string) => {
    return JSON.stringify(localStorage.getItem(key));
  };

  const returnPersistentValue = (key: string) => {
    if (getValue(key) === "null") return "";
    else return getValue(key).replace('"', "").replace('"', "");
  };

...

The reason for this error is likely due to the fact that Vercel's deployment system operates on the server-side, causing both window and localStorage to be undefined, resulting in the reference error. How can I go about resolving this issue?

Answer №1

To ensure the proper functioning of the code, it is important to first verify the existence of the window:

  const storeData = (key: string, value: string) => {
    return typeof window !== "undefined" ? localStorage.setItem(key, value) : undefined;
  };

  const retrieveData = (key: string) => {
    return typeof window !== "undefined" ? JSON.stringify(localStorage.getItem(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

Create an interface property that can accommodate various disparate types

In a React component, I am looking to use an external type (from react-hook-form) that can accommodate 3 specific types representing an object with form values. I initially thought about using a union type for this purpose, but encountered issues when pas ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

The young one emerges within the SecurePath component temporarily

Setting up authorization in React has been a priority for me. Ensuring that users cannot access unauthorized pages within the application is crucial. To achieve this, I have created a custom component as shown below. import { ReactNode } from "react&q ...

Having trouble iterating over fields of an interface in TypeScript?

I am currently facing an issue while trying to loop through the keys of an object that contains an interface. TypeScript seems to be unable to recognize the type of the key. interface Resources { food?: number water?: number wood?: number coal?: n ...

Next.js encountered an issue when trying to read properties of null, specifically the 'push' property, resulting in a TypeError

I am utilizing the sweetalert2 library for displaying popups: export default function Home() { const MySwal = withReactContent(Swal) useEffect(() => { MySwal.fire({ showConfirmButton: false, customClass: { ...

Sharing data with child components in Next.js through getStatisticProps

Is it possible to use getStaticProps only in the pages area, or can I also utilize a template from the components? I am looking to pass data from pages/index.js export default function Home({posts}) { return ( <div> <Head> ...

Discover the proper technique to display an error message in cases where no data is detected during the filtering process

I'm currently working on a component that involves search filtering and dropdown filtering. The filtering functionality is working fine, but I'm struggling to determine where to display an error message if no data is found during the filtering pr ...

Creating an executable JAR for your Next.js application: A step-by-step guide

Is there a way to ensure that my Next.js file can run seamlessly on any computer without the need for reinstallation of all modules? In my folder, nextjs-node, I have the following subfolders: components lib public node_modules page style package.json I ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Why does the Formik form only validate after the second button click in this React Hooks, TypeScript, Formik, NextJS setup?

Looking for fresh perspectives on my code. The issue lies in the fact that it takes two submission attempts to validate the data inputted into a form successfully. It appears that the post request to Airtable happens before the validation schema, resulting ...

Function Type Mapping

I am in the process of creating a function type that is based on an existing utility type defining a mapping between keys and types: type TypeMap = { a: A; b: B; } The goal is to construct a multi-signature function type where the key is used as a ...

Creating Empathetic User Experiences with Next 12 and SWC: A Guide to Harnessing import.meta.url

In my Next.js 12 App with the Rust Compiler, I am utilizing Jest and WebWorkers. In one of my files, I am using import.meta.url. to create the worker. The issue arises when Jest throws an error, stating that import.meta.url cannot be used outside of an ES ...

Using Tailwind CSS to center a NexJS <Image /> component within a modal

In an effort to style my MapBoxGL popup content, I am working on aligning the text above the image to the left and centering the image below within the popup. As shown in the image below, this is currently proving to be a challenge as I transition from usi ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Create a rectangle on the canvas using the Fabric.js library in an Angular application

I am attempting to create a rectangle inside a canvas with a mouse click event, but I am encountering some issues. The canvas.on('selection:created') event is not firing as expected. Below is my code: let can = new fabric.Canvas('fabricCanv ...

Looking to implement server-side rendering with Next.js using [id].js in headless WordPress? Utilize GraphQL to fetch a single page from WordPress and create a service in the format of service/[id

I am currently working on a Next.js project that utilizes Apollo GraphQL to fetch data from the backend. My goal is to render the page using server-side rendering, but I am facing an issue with calling the backend within the getServerSideProps due to the ...

A custom hook is not functioning as expected

I've encountered an issue with the useCart() function, as it's giving me an error message stating that it is not a function. Here is the code snippet where I'm using it: "use client"; import React, { createContext, useReducer, use ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

Angular makes it easy to extract multiple parameters from a URL

In the process of developing a basic Angular application using TypeScript, I have encountered an issue. Within my project, there is a URL structure like this: www.example.com/api/1/countries/Italy/ My goal is to extract the values 1 and Italy from this U ...

Do I have to wait for the HTTP get request to access the fetched object property?

I am currently working with Angular and TypeScript on a dish-detail component that is accessed through 'dishes/:id' The dish object returned has a property called components, which contains an array of objects with two properties: id: type stri ...