The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error.

Here's the code snippet (./src/utils/secureLocalStorage.js):

import SecureStorage from 'secure-web-storage'
import CryptoJS from 'crypto-js'

const SECRET_KEY = process.env.REACT_APP_SECRET_KEY

let secureLocalStorage = null

try {
   secureLocalStorage = new SecureStorage(localStorage, {
   hash: function hash(key) {
   key = CryptoJS.SHA256(key, SECRET_KEY).toString()
   return key
},
encrypt: function encrypt(data) {
  data = CryptoJS.AES.encrypt(data, SECRET_KEY).toString()
  return data
},
decrypt: function decrypt(data) {
  try {
    data = CryptoJS.AES.decrypt(data, SECRET_KEY).toString(
      CryptoJS.enc.Utf8
    )
    return data
  } catch (error) {
    console.error('Error decrypting data:', error)
    return null
  }
},
})
} catch (error) {
  console.error('localStorage is not available:', error)
 }

export default secureLocalStorage

The error message appears in my terminal as shown below:

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

Answer №1

There are a couple of issues at play here. Firstly, let's delve into the reason behind the error you're encountering. NextJS is primarily utilized for Server Side Rendering (SSR). This implies that the code needs to be executed on the server in order to generate a response. Since it operates on the server, access to the window object is restricted as it is exclusive to browsers. Consequently, objects like localStorage are unavailable.

Furthermore, attempting to establish secure storage utilizing localStorage poses another challenge. Given that localStorage functions on the client-side, the SECRET_KEY would need to be transmitted to the client. This compromises the integrity of secure storage mechanisms.

If you can provide insights into your application or specific use case, either I or someone within this community might offer alternative suggestions.

You may find this resource beneficial.

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

Generate a QR code image from the API and then proceed to send it in the next 13 steps

Using the API from URL parameters, I create custom QR codes that are used by other applications. However, I am unable to find a way to send a buffer using NextResponse. Is it possible to send an image in the next 13 APIs? This is my code from the previous ...

Next js is repeatedly calling a Firestore document in multiple instances during the fetching process

In my Next js 13 project, I am facing an issue while fetching a single document with an id from Firebase. Instead of returning just one read (which is expected since I'm fetching a single doc), it is returning multiple reads, sometimes ranging from 2 ...

React: State does not properly update following AJAX request

I'm currently facing a challenge in my React project where I need to make two AJAX calls and update the UI based on the data received. Below is the implementation of my render method: render() { if (this.state.examsLoaded) { return ( ...

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

Developing a hybrid SSG using NextJS and Magnolia CMS technology

Recently, I've been delving into the Magnolia CMS NextJS hybrid SSG project. There's a boilerplate code for a page called pages/[[pathname]] that effectively generates static content and paths for all pages added in the admincentral app. It works ...

Every time I utilize SessionProvider from next/auth/react, I encounter an error that states: "TypeError [ERR_INVALID_URL]: Invalid URL."

While working on my application in Next.js, I decided to incorporate NextAuth into the project. However, when attempting to use SessionProvider as instructed in the documentation, I encountered an error message stating: "TypeError [ERR_INVALID_URL]: Invali ...

JavaScript condensed into a single table cell rather than occupying an entire webpage

Hey there, I have a simple question that I can't seem to find the answer to anywhere. I'm working on a JavaScript function that pulls data from my database and I want it to display in one cell of a table instead of outputting to the entire page. ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

Issues arises when trying to send an array of favorite items to a view using PHP and AJAX

Could you please assist me with sending this array of favorites to PHP using AJAX? I keep encountering a 403 forbidden error, even though the path seems correct. It's possible that I am missing something here, any guidance or help would be highly appr ...

Error 404: Next.js Navigation Not Detected

I've recently launched a new Next.js project and I'm currently working on implementing client-side navigation. However, I am facing an issue where I am unable to navigate to routes other than "/". Layout.js : import "../styles/globals.css&q ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

Leveraging various routes to access data with a shared VueJS 3 component

Could you please review this code snippet: It displays two routes that utilize the same component to fetch content from an API. Main.js const router = createRouter({ history: createWebHistory(), routes: [ { path: "/route1& ...

Bring back enhanced assortment using Mongoose

I am currently working with a stack that includes nodejs, express, mongoose, and angularjs. My task involves updating a collection called Lists which contains various properties, including an array of items. The issue I am facing is that when I push a new ...

What is the best way to augment an AJAX array response with additional data?

I'm working on an AJAX request and I need to add additional properties to the response I receive. Can anyone offer some guidance? Here is the AJAX request code I'm using: var form_data = {}; $.ajax({ type: "GET", url: "../../../sample_ ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Encapsulating the React Material-ui Datepicker and Timepicker OnChange event callback functionging

I'm new to React and currently incorporating Material-UI into my project for additional UI components. I've noticed some repetitive code that I'm finding difficult to refactor due to constraints within a Material-UI component's implemen ...

Assistance with Jquery for toggling checkboxes when labels are clicked

I'm currently working on a feature that allows for checking and unchecking checkboxes upon label click. You can find my Jsfiddle here: http://jsfiddle.net/PTAFG/1/ The HTML structure cannot be altered Here is the snippet of my HTML: <div style= ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...