import User from '../modal/Model.js'
import { createSecretToken } from '../util/SecretToken.js';
export const Signup = async (req, res, next) => {
// console.log(req.body)
try {
const { email, password, username, createdAt } = req.body;
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.json({ message: "User already exists" });
}
const user = await User.create({ email, password, username, createdAt });
console.log(user._id)
const token = createSecretToken(user._id);
console.log(token)
localStorage.setItem('token', token);
res
.status(201)
.json({ message: "User signed in successfully", success: true, user });
next();
}catch (error) {
console.error(error);
}
};
I am trying to store the token key in localStorage but it showing local stroage is not define
.
As in above jsx component I am trying store it in localStorage for auth.
2
Answers
LocalStorage is something present in browsers available in the window object and it seems like you are using nodeJS environment.
Node.js is not a browser-based code environment. Usually, web browsers (like Google Chrome, Safari, FireFox, etc.) use
localStorage
to store small chunks of data in the user’s computer securely on the website.In browsers, when you use
localStorage
like the following example:This is a built-in function that creates a file to that website’s domain, storing whatever the developer wants in that file to save for later.
Now, because Node.js is not a web browser, it has no built-in way of storing data for later. The creators of Node.js have not fully implemented
localStorage
as a default method yet, because there is currently no reason to do so.There are many ways to mimic this method. Here are 2 examples to store data in Node.js:
Example 1
For Example 1 I’m using the package
fs
to create a file calledlocalStorage.json
(you can call this whatever you want though) and I will create my own function to write JSON data to that file the same waylocalStorage
would.Example 2
For this example, I’ll use the NPM package node-localstorage. This package allows you to use
localStorage
the same exact way you would in your browser.