user616
user616

Reputation: 855

fastify and prisma with postgres session storage

I am building a nodejs api that uses fastify, Prisma and Postgres. I have the API working with fastify-cookies and fastify-session and i can get cookies just fine but i need to be able to store the session cookies in the database. I saw a tutorial on doing this but it was without prisma, so im lost on how to connect fastify-session to the Prisma database pool.

I user the prisma client to connect to the database to do my normal calls in my routes, const data = await prisma.model.create({});

server.js

const fastify = require('fastify')({ logger: true });
const PORT = process.env.PORT || 3000;

// Session state
fastify.register(require('./sessions'));

// Register all our routes here.
...

// Startup code for the fastify server.
const start = async () => {
  try {
    await fastify.listen(PORT, '0.0.0.0');
  } catch (error) {
    fastify.log.error(error);
    process.exit(1);
  }
};

// Start the fastify server.
start();

sessions.js

const cookie = require('fastify-cookie');
const session = require('fastify-session');
const fp = require('fastify-plugin');

/**
 * @param {import('fastify').FastifyInstance} fastify
 */
const plugin = async (fastify) => {
  // All plugin data here is global to fastify.
  fastify.register(cookie);
  fastify.register(session, {
    secret: process.env.SESSION_SECRET,
    store: new SessionStore({
      tableName: 'UserSession',
      pool: ???,   <--------------------------------- how to connect?
    }),
    saveUninitialized: false,
    cookie: {
      httpOnly: true,
      secure: false,
    },
  });

  fastify.addHook('preHandler', (req, reply, next) => {
    req.session.user = {};
    next();
  });
};

module.exports = fp(plugin);

Upvotes: 1

Views: 1260

Answers (1)

Tasin Ishmam
Tasin Ishmam

Reputation: 7268

If you want to use the Prisma connection pool you would have to create a session storage library similar to connect-pg-simple or modify the codebase to accept a Prisma connection. This is definitely a non-trivial implementation and I don't think it would make a lot of sense without exceptional circumstances.

I would suggest creating a new pg.Pool or pgPromise instance and connecting with that like it was shown in the tutorial video you linked to. There's no reason you can't have two separate connection pools open to the same database (One with Prisma and one with pg.Pool)

Upvotes: 1

Related Questions