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

Unexpected behavior observed with Angular Toggle Button functionality

Having trouble implementing toggle functionality in Angular where different text is displayed when a button is toggled. I keep getting an error in my code, can anyone assist? See the code below: HTML <tr> <td>Otto</td> <td> ...

Embrace the flexibility of using Next.js with or without Express.js

Recently, I started the process of migrating a project from create-react-app to next.js. However, I am facing uncertainty when it comes to migrating the backend of the project. Currently, my backend is built with an express server. In next.js, there are p ...

How come the props aren't being passed from the parent to the child component? (React / TypeScript)

Learning TypeScript for the first time and facing an issue with passing props from parent to child components. The error seems to be related to the type of props, but I'm not sure how to fix it since all types seem correct. Error message: "Property ...

Unlock the power of TypeScript's inheritance by utilizing static methods for type

In my TypeScript project, I have two classes: BaseModel and HotelModel. The HotelModel extends the BaseModel class, which provides static methods like findById, all, etc. export default class BaseModel { private collection:string _id:string | undefine ...

Images on NextJS are failing to resize properly in Next 13

I have been facing challenges with optimizing image sizes for different screen resolutions using the NextJS Image component. Currently, all images seem to be loading at their largest size on various screens. Below is a screenshot showing the resolution t ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

Intriguing flashing dark streak, reminiscent of a boundary within NextJS

I have recently encountered an unexpected issue with my full-width video header that worked perfectly on multiple pages before. Strangely, a thin black line has appeared around the bottom and right side of the div (.header) containing the video, even thoug ...

Custom Map Typescript Interface

Here is the structure of my interface: export interface IMyMap { [index: string]: RefObject<HTMLElement>; } This interface was created following the guidelines in the documentation: Indexable Types I am trying to implement this interface in a Re ...

Struggling to retrieve the image URL from a TypeScript file

I'm currently developing a basic app in Ionic that will include a feature to display a list of registered users along with their profile pictures. These profile images are stored in Firebase storage. Although I have successfully retrieved the URLs fo ...

Using TypeScript to return an empty promise with specified types

Here is my function signature: const getJobsForDate = async (selectedDate: string): Promise<Job[]> I retrieve the data from the database and return a promise. If the parameter selectedDate === "", I aim to return an empty Promise<Job[] ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...

Reverting a React-Select child component back to its default values from the parent component

I am facing an issue with a parent component (Membership) that includes a child component (AboutYou). The parent component handles form submission using a button, which also triggers a reset action. The AboutYou child component contains a React-Select inp ...

Using callback functions to initiate server actions

Currently, I am diving into server actions within the Next.js 14 app router. Server actions are mainly used for making post requests to the server. But, I am curious if there is a way for server actions to trigger a function on the client side. My goal is ...

The project's dependencies must include '@material-ui/core'

Currently, I am attempting to integrate an Instagram-style like button into a component. However, every time I try to import the necessary components, I encounter this error message: "'@material-ui/core' should be listed in the project' ...

It appears there was a mistake with [object Object]

Hey there, I'm currently working with Angular 2 and trying to log a simple JSON object in the console. However, I keep encountering this issue https://i.stack.imgur.com/A5NWi.png UPDATE... Below is my error log for reference https://i.stack.imgur.c ...

What is the simplest way to incorporate Vue with Typescript, without the need for a complex build setup?

I've been spending the last couple of days experimenting with my basic ASP.NET Core website set up for Typescript 2.9, but unfortunately, I haven't made much progress. My main goal is to keep the front-end simple, with just single Vue apps on eac ...

Error TRPCClient: The unexpected presence of the token "'<'", ""<!DOCTYPE "... invalidates the JSON format within Next.JS

Encountering an error in the authentication call back page: TRPCClientError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON in Next.JS. The issue occurs in src/app/auth-callback/page.tsx and here's the relevant code ...

"Exploring the seamless integration of Next.js and Material UI for stunning web

I have encountered an issue while using Next.js and Material-UI(@mui/core) to build a website. Everything works perfectly when I run it with next dev, but the styles get messed up when using next build && next start. In addition to Material-UI, I ...

Enums are not recognized by TypeScript when used within an array

I have defined an enum as follows: export enum Roles { ADMIN, NONE; } An object is being used which utilizes this enum. The structure of the object is: export interface User { name: string; roles: Roles[]; } Upon fetching this object via a web r ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...