Please guys come to my aid. I have battling this issue for weeks now.
I am currently taking the Ben Awad Full-Stack course and I’m having trouble with the express-session part. I’m unable to access the userId that I stored in req.session. Whenever I attempt to access another router (such as /me), I receive undefined when trying to access req.session.userId. Additionally, I’ve noticed that the req.session.id changes every time I try to access another route.
Here is the link to the GitHub repository: https://github.com/backendbro/reddit-jnr
index.ts
const RedisStore = require("connect-redis").default;
const redisClient = await createClient()
await redisClient.connect()
app.use(
session({
name:"qid",
store: new RedisStore({
client: redisClient,
disableTouch:false,
ttl: 60*60*24*365
}),
cookie:{
maxAge: 60*60*24*365,
httpOnly:false,
sameSite:"lax",
secure: __prod__
},
secret: "t4t3t3tg432v342242#$@#@$@#@$",
resave:false,
saveUninitialized:true
})
)
user.ts
@Mutation(() => UserResponse)
async login (
@Arg ('options') options: UsernamePasswordInput,
@Ctx() {em, req}: MyContext
) : Promise <UserResponse> {
const user = await em.findOne(User, {username: options.username})
if (!user) {
return { errors: [{
field:"username",
message:"that username does not exists"
}]
}}
const valid = await argon2.verify(user?.password, options.password)
if (!valid) {
return {
errors: [
{
field:"password",
message:"incorrect password"
}
]
}
}
req.session.userId = user.id
req.session.save()
console.log(req.session.id)
return {user}
}
@Query(() => UserResponse, {nullable:true})
async me(
@Ctx() {em, req}: MyContext
) : Promise<UserResponse>{
console.log(req.session.id)
const userId = req.session.userId
if (!userId) {
return {
errors:[{
field:"req.session.userId",
message:"there is no userId in req.session"
}]
}
}
const user = await em.findOne(User, {id: userId})
if (!user) {
return { errors: [{
field:"user",
message:"the suppose current user does not exist in the database"
}]
}}
return {user}
}
custom.d.ts
declare namespace Express{
interface Request {
session: Session & Partial<SessionData> & { userId?: number|string };
}
}
types.ts
export type MyContext = {
em: EntityManager<IDatabaseDriver<Connection>>;
req: ExpressContext['req']
res: ExpressContext['res'];
}
I have searched the internet extensively for answers but my efforts were abortive. I expect to get a solution which I can apply to my code to help me access my userId throughout my application using req.session.userId.
Nzubechukwu Ukagha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.