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

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

Try enabling automatic status bar filling in Onsen UI when working with AngularJS

Completely new to AngularJS, I am trying to understand how to use ons.enableAutoStatusBarFill(); in order to prevent my menus from overlapping the status bar. This is how I have set up my controller: var mod = ons.bootstrap('app', ['onsen& ...

Challenges arise with CSS alignment when adding d3.js charts to a webpage

I'm puzzled by the empty space that appears between the left column (highlighted in the image) and the header. This peculiar gap only seems to occur when the middle column is filled with a chart. I've scrutinized the code using Chrome Developer t ...

Encountering a "NextJS Google Drive API error due to Insufficient Permission when using Service

I am currently developing a basic NextJS application with the goal of displaying files from a specific Google Drive folder. The Google Drive folder belongs to my personal account and is shared with a Service Account that I created in Google Cloud Platform ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

Enhance the appearance of the jQuery document.ready function

I'm attempting to customize the jQuery document.ready function <html> <head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript> $(function() { c ...

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

What is preventing me from mapping an array to Material UI Chip components?

I'm currently working with Next.js and I'm trying to map an array of elements to Material-UI chip components. However, when I compile the code, I encounter the following error: Error: Element type is invalid: expected a string (for built-in comp ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...

Using jQuery to transfer data via POST method

I'm currently working on integrating a third-party tool into our website. The tool requires the use of a form with the post method to send data to their site. Is there a way for me to replicate this action without relying on the form tag? I am not ver ...

React Big Calendar - Creating a personalized property for a unique perspective

My React Big Calendar library has a custom view for the year. <Calendar localizer={localizer} events={events || []} startAccessor="start" endAccessor="end" defaultView="year" views={{ year: YearView }} c ...

Javascript enables dynamic field addition to tables

I have JSON data that needs to be displayed in an HTML table. To input the values, I have individual fields for firstname, lastname, email, and phone number, along with an "Add Row" button. When I click the "Add Row" button, I want the entered values to b ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

Colorful Paper Trail Logging

After stumbling upon a post on the internet, I discovered that Papertrail offers the ability to log using ANSI colors. This is particularly appealing to me as my node.js app generates numerous logs, and adding color helps me decipher the information during ...

What steps can be taken to fix the issue of "failed to solve: process "/bin/sh -c yarn install --frozen-lockfile" while constructing a Docker file?

I am attempting to dockerize my next.js app and have encountered an error while building the Dockerfile. Below is the Dockerfile I am using: FROM node:18-alpine AS BUILD_IMAGE WORKDIR /app COPY package.json yarn.lock ./ RUN yarn install --frozen-lockfile ...

No data provided in nested parameters for Ajax post request

I am attempting to send an Ajax request to my rails controller using Ajax. $.ajax({ url: '/vulnerabilities/export', type: 'GET', processData: false, data: {export: {ids: this.refs.table.state.selectedRowKeys }} }); When there ...

Dealing with errors in getServerSideProps in Next.js by utilizing next-connect

Recently, I've been working with Next.js and utilizing the next-connect library to manage middlewares in my project. However, I'm encountering some difficulties when it comes to handling errors while using multiple middlewares within the getServ ...