Store the user's login credentials securely in the browser's local storage

Currently, I am implementing user authentication in Node Express with EJS using JWT. The generated token is stored in cookies using the following code:

res.cookie('authorization', token, {maxAge: 3 * 60 * 60 * 1000});

During verification, I can easily retrieve the token from the cookies:

req.cookies['authorization'];

While this method eliminates the need for authentication-related code on the frontend, I have come across recommendations to store tokens in the browser's local storage instead:

localStorage.setItem("authorization", "..object..");

This suggests that the localStorage code is meant for the frontend, indicating that the token has to be sent to the frontend and then saved in localStorage.

Is there a way to achieve this without sending the token to the frontend?

Answer №1

You have a good understanding of working with cookies. However, when it comes to using local storage, remember to send the token back to the front-end after verification and attach it to every subsequent request. Local storage can be accessed by JavaScript and is susceptible to XSS attacks. It's safer to stick with cookies that have the HTTPOnly flag enabled.

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

Setting up Twilio integration on a Parse Server deployed on Heroku

I am currently running a successful Parse Server on Heroku and am attempting to set up my Twilio cloud code. However, the moment I include var twilio = require('twilio')(twilioAccountSid, twilioAuthToken); in my main.js file, the application stop ...

Error encountered in ExpressJS: Headers modification on ServerResponse.OutgoingMessage.setHeader is invalid

Encountering an error on my Express 4 app signup user account, where I receive the following message: Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11) This error only occurs when at ...

Exploring the find method within a Mongoose Schema for an array of objects

My Node Application has the following Mongoose Schema var expenseSchema = new Schema({ particular : String, date : {type : Date, default: Date.now}, paid_by : String, amount : Number, month : String }); var roomSchema = new Schema({ ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Tips for incorporating routes in Polka.js in a way that resembles the functionality of express.Route()

One of the challenges I am facing is trying to import route logic from another file in my project. While using Express.js, this could be done easily with express.Route(). However, when attempting polka.Route(), an error occurs stating that Route doesn&apos ...

Is it possible to access an HTML element using NodeJS without relying on external libraries?

My current challenge involves accessing and changing the innerHTML of an HTML element. My application must connect to a database and perform CRUD operations, which worked successfully when connected to the database via cmd and localhost 3000. However, I en ...

Open a file using the fs module while ensuring the original file is preserved

I've been working on a NodeJS API that sends emails. Each time I need to send an email, I use the index.handlebars template. To customize the template before sending the email, I utilize the Node File System (fs) module to readFileSync() and then ap ...

Setting headers in Node.js after they have already been sent to the client is not allowed

I'm currently enrolled in a node.js course on Udemy which seems to be outdated. I've encountered some errors that I'm struggling to resolve. Here's what I've tried so far: using next(); adding return res inside all if statements ...

Generate a customized API key using Node.js and save it in Redis

I'm currently working on setting up an API with Node and my goal is to securely store the API key/access token in a Redis database. What is the most effective way to create a one-of-a-kind API key/access token that can be stored as the key in the Red ...

The Sequelize model has both a Unique constraint and paranoid behavior enabled

I currently have a table with a unique constraint on a field along with paranoid enabled. For example, in the scenario presented below, the brand name serves as the unique value. class Brand extends Model { static init(sequelize) { retu ...

CORS blocking is preventing Next JS due to lack of HTTP OK response status

When utilizing GraphQL to facilitate communication between a client and server across different domains, I took the necessary steps to enable CORS on my API website by referring to the documentation provided by Vercel. However, it appears that I am encount ...

Having trouble configuring individual route files in Express JS

I'm having trouble separating my login route from the default app.js and route/index.js files. When I try to access localhost:3000/login, I keep getting a 404 Not Found error. I've searched on StackOverflow for similar questions and tried follow ...

I encountered an npm start error while trying to run my React JS application in VS Code

Hey everyone, I could really use some help. I've finished all the coding part of my project but when I try npm start at the end, I keep getting errors. Error: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\yateesh\D ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

Using Promises Across Multiple Files in NodeJs

Initially, I had a file containing a promise that worked perfectly. However, realizing the need to reuse these functions frequently, I decided to create a new file to hold the function and used module.export for universal access. When I log crop_inventory ...

The interface 'Response<ResBody>' has been incorrectly extended by the interface 'Response'

I am currently working with typescript and express in a node.js environment. Whenever I compile my code, I encounter the following bug: node_modules/@types/express-serve-static-core/index.d.ts:505:18 - error TS2430: Interface 'Response<ResBody>& ...

The function socket.rooms returns an array with no elements

My server side code is as follows: io.on('connection', function (socket) { socket.join('main'); console.log(socket.rooms); /* ==> [] */ console.log(socket.adapter.rooms); /* ==> { '5incJ4hA4tKyJHUjAAAA&apo ...

What causes the ignoring of config.proxy in axios requests while working on a webpack project?

My objective I am aiming to make a request using [email protected] with full efficiency through an http proxy (squid). My project is built on Vue and uses the webpack template. I initialized it with vue init webpack proxytest The challenge Despite ...

How about I visit the campgrounds/edit page for a change?

In this get route, the previous link it was redirected from is stored in the req.session object under returnTo. Once redirected, it goes to the /login and we are able to view the object in the console. router.get('/login', (req, res) => { ...

Passing a Scope to ES6 Template Literals: How to Ensure they are Interpreted Correctly?

I've recently started utilizing template literals to create an error generator. Although I have functional code, I find myself having to define the list of potential errors within the constructor scope, and this is not ideal for me. Is there a way t ...