简体   繁体   中英

How do i use cookies on the client side to display user information after passport js local user auth on the server side?

I am using passport js and express session for local user auth, and i want to use cookies to display user information such as first name or email on the client side thats running on vue js, after the user has successfully signed up using passport js on the server side. How do i accomplish this?

There are several ways to do this:

  1. Use an API endpoint, like /me , that returns the logged-in user's user information. Whenever a user's information needs to be displayed, make a call to /me and parse what's returned.

  2. Use a JWT as your cookie and include user information in it. However, once user data changes, you'll need to update the user's cookie. This might be okay for relatively static data like names that do not change often. However, for data that changes frequently this might not be the most convenient option. Also keep in mind that whatever is in a cookie is sent by the user on each request and can take up extra bandwidth or even exceed the maximum header length if too much is loaded into the cookie.

You can save cookies to the user's pc from client side using

document.cookie="email:loremipsum@dolor.com"

and you can read it from client side as

let x = document.cookie

if you want to read it from the express server, you can use cookie-parser so npm install cookie-parser and then require it into your express server and do app.use

var express = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

to read the cookies at express server,

app.get('/',(req,res)=>{
   console.log(req.cookies.email)
});

this would display the cookie at server side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM