Struggling to implement a login system using GraphQL and Express, but facing issues with session persistence. Despite logging in, req.session.userId
remains undefined.
Code snippet:
(async () => {
await connect(process.env.MONGO_URI!, { dbName: "example" });
const app = express();
app.use(
cors({
origin: [__clientUrl__, "https://studio.apollographql.com"],
credentials: true
})
);
app.use(
session({
name: "qid",
secret: process.env.SESSION_SECRET!,
store: MongoStore.create({
mongoUrl: process.env.MONGO_URI,
dbName: "example"
}),
saveUninitialized: false,
resave: false,
cookie: {
maxAge: 6.048e8,
httpOnly: __prod__,
sameSite: "lax",
secure: __prod__
}
})
);
const server = new ApolloServer({
schema: await buildSchema({
resolvers: [HelloResolver, UserResolver],
validate: false
}),
context: ({ req, res }) => ({ req, res })
});
await server.start();
server.applyMiddleware({
app,
cors: {
origin: [__clientUrl__, "https://studio.apollographql.com"],
credentials: true
}
});
app.listen(__port__, () =>
console.log(
`🚀 Server started at http://localhost:${__port__}${server.graphqlPath}`
)
);
})();
Login Mutation using TypeGraphQL:
@Mutation(() => User, { nullable: true })
public async login(
@Arg("username") username: string,
@Arg("password") password: string,
@Ctx() { req }: Context
) {
const user = await UserModel.findOne(
username.includes("@") ? { email: username } : { username }
);
if (!user) return;
if (!(await verify(user.password, password))) return;
req.session.userId = user._id;
return user;
}
Additionally, cookies were enabled in the GraphQL Explorer and specified headers were set: https://i.sstatic.net/npvAt.png