mcclosa
mcclosa

Reputation: 1455

Next-Auth Store Session in Redis

I'm coming from express, never using next-auth before but unsure how to store user session in a redis database.

On express, I would have done the following;

import express from 'express';
import session from 'express-session';
import connectRedis from 'connect-redis';
import Redis from 'ioredis';
import { __prod__, COOKIE_NAME } from './constants';

const main = async () => {
  const RedisStore = connectRedis(session);
  const redis = new Redis(process.env.REDIS_URL);

  app.use(
    session({
      name: 'qid',
      store: new RedisStore({
        client: redis,
        disableTouch: true,
        ttl: 1000 * 60 * 60 * 24 * 365, // 1 year
      }),
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 365, // 1 year
        httpOnly: true,
        sameSite: 'lax',
        secure: __prod__,
        domain: __prod__ ? process.env.DOMAIN : undefined,
      },
      saveUninitialized: false,
      secret: process.env.SESSION_SECRET,
      resave: false,
    }),
  );
};

main()

[...nextauth].ts

import NextAuth, { type NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { prisma } from "../../../server/db/client";

export const authOptions: NextAuthOptions = {
  callbacks: {
    session({ session, user }) {
      if (session.user) {
        session.user.id = user.id;
      }
      return session;
    },
  },
  adapter: PrismaAdapter(prisma),
  providers: [
    CredentialsProvider({
      async authorize(credentials, req) {
        //
      },
    }),
  ],
};

export default NextAuth(authOptions);

I can't find any implementations of redis in NextAuth, other than using Upstash for caching, but not for sessions.

Upvotes: 5

Views: 5162

Answers (1)

quanhua92
quanhua92

Reputation: 66

I made an adapter for Next Auth that uses ioredis to store data in the Hash data structure. In the Upstash adapter, they store the data with JSON.stringify. In my adapter, I use the Hash data structure so it is easier to extend the User object. You can take a look at this repository.

Upvotes: 3

Related Questions