benawad / lireddit

https://youtu.be/I6ypD7qv3Z8
MIT License
1.77k stars 467 forks source link

Redis v4 config problem & solution (so you don't have to sweat) #53

Open Chriskuiper1 opened 2 years ago

Chriskuiper1 commented 2 years ago

When installing Redis @ 1:41h and testing the auth cookie, graphql will crash. This is because the new version of Redis (v4) doesn't support the code from the tuturial. The codeblock below will fix this. You can find the full documentation here: https://www.npmjs.com/package/connect-redis

const session = require("express-session");
let RedisStore = require("connect-redis")(session);

const main = async () => {
    const orm = await MikroORM.init(microConfig);
    await orm.getMigrator().up();

    const { createClient } = require("redis");
    let redisClient = createClient({ legacyMode: true });

    redisClient.on("connect", () => console.log("Connected to Redis!"));
    redisClient.on("error", (err: Error) =>
        console.log("Redis Client Error", err)
    );
    redisClient.connect();

    const app = express();

    app.use(
        session({
            name: "qid",
            store: new RedisStore({
                client: redisClient,
                disableTouch: true,
            }),
            cookie: {
                maxAge: 1000 * 60 * 60 * 24 * 365 * 1, // 1 year
                httpOnly: true,
                sameSite: "lax",
                secure: __prod__, // cookie only works in https
            },
            saveUninitialized: false,
            secret: "bruhhhh",
            resave: false,
        })
    );
tonype commented 1 year ago

Thank you! I found the determining thing for me that got it to work was passing in legacyMode: true into createClient.

AbhinavHaridas commented 1 year ago

Thanks! I went through stack overflow and asked a lot of questions to chat gpt. But this is the only one that worked. :)

mhd-hi commented 1 year ago

I still get this error:

let RedisStore = require("connect-redis")(session);
                                         ^

TypeError: require(...) is not a function
    at Object.<anonymous> (C:\Users\moham\Documents\Projects\lilReddit\dist\index.js:26:42)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:22:47
[nodemon] app crashed - waiting for file changes before starting...

in yarn dev console.

Here's my code:

import "dotenv/config";
import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import microConfig from "./mikro-orm.config";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import "reflect-metadata";
import { UserResolver } from "./resolvers/user";
import { PostResolver } from "./resolvers/post";
import { MyContext } from "types";

const session = require("express-session");
let RedisStore = require("connect-redis")(session);

const main = async () => {
  const orm = await MikroORM.init(microConfig);
  await orm.getMigrator().up();

  const { createClient } = require("redis");
  let redisClient = createClient({ legacyMode: true });

  redisClient.on("connect", () => console.log("Connected to Redis!"));
  redisClient.on("error", (err: Error) =>
    console.log("Redis Client Error", err)
  );
  redisClient.connect();

  const app = express();
  app.use(
    session({
      name: "qid",
      store: new RedisStore({
        client: redisClient,
        disableTouch: true,
      }),
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 365 * 1, // 1 year
        httpOnly: true,
        sameSite: "lax",
        secure: __prod__, // cookie only works in https
      },
      saveUninitialized: false,
      secret: "bruhhhh",
      resave: false,
    })
  );

My tsconfig:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "./src",
    "paths": {
      "*": ["*", "src/*"]
    },
    "types": ["node", "express", "express-session"]
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"]
}

I appreciate any help

mhd-hi commented 1 year ago

Found the fix : https://www.npmjs.com/package/connect-redis

princewillopah commented 1 year ago

@mhd-hi, how did the link help? what did you do differently. i have similar issue. Thanks