I use typescript. I want to implement a session based authentication system. So, Ive decided to use fastify/session. And Prisma for storing the sessions. My problem is when I request to “/” path (which you can see the below) it doesnt return anything. My postman shows only “Sending request…” and nothing is returning. But database creates the session. And in console I can see the sessionId (which i printed in console.) and its matches with the sessionId in database. What can I do to solve this?
My index.ts file which I implement the fastify and sessionStore:
import Fastify, { FastifyReply, FastifyRequest } from "fastify";
import fastifyCookie from "@fastify/cookie";
import fastifySession from "@fastify/session";
import { db } from "./libs/db";
const fastify = Fastify();
const PORT = Number(process.env.PORT) || 3000;
fastify.register(fastifyCookie);
fastify.register(fastifySession, {
store: {
set: async (sid: string, session: object) => {
await db.session.upsert({
where: { sid },
update: { session: JSON.stringify(session) },
create: { sid, session: JSON.stringify(session) },
});
},
get: async (sid: string) => {
try {
const storedSession = await db.session.findUnique({ where: { sid } });
return storedSession ? JSON.parse(storedSession.session) : null;
} catch (error) {
return null;
}
},
destroy: async (sid: string) => {
await db.session.delete({ where: { sid } });
},
},
cookieName: "sid",
secret: "supersecretkeysupersecretkeysupersecretkeysupersecretkey",
cookie: {
maxAge: 1000 * 60 * 60,
secure: process.env.NODE_ENV === "production",
},
});
fastify.get("/", (req: FastifyRequest, res: FastifyReply) => {
console.log(req.session.sessionId);
return { success: "Test sucess!" };
});
try {
fastify.listen({ port: PORT });
console.log(`Server is listening port ${PORT}`);
} catch (error) {
fastify.log.error(error);
process.exit(1);
}
My schema.prisma file:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model Session {
sid String @id @default(uuid())
session String
}
And what caught my eye is that in index.d.ts file which source code of the fastify/session the declaration of get, set and destory method are like this:
set(
sessionId: string,
session: Fastify.Session,
callback: Callback
): void;
get(
sessionId: string,
callback: CallbackSession
): void;
destroy(sessionId: string, callback: Callback): void;
All of them return void, is it the case? But if get method returns anything how can i indicate that what is the session which i got brought from the database or something? Or my Session schema in prisma.schema file, is it the case?
Kaan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.