Skip to content

Oak context doesn't retain the session set in one middleware #691

@primasghar

Description

@primasghar

I am facing a weird issue that when I set the session in one middleware, it's value in undefined in other. Even in the same middle ware functions it is undefined.

Here is how my app file looks like

import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { authMiddleware } from "./middlewares/authMiddleware.js";
import { errorMiddleware } from "./middlewares/errorMiddleware.js";

import { router } from "./routes/routes.js";

const app = new Application();
app.use(
  oakCors({
    origin: "http://localhost:5173",
  }),
);
app.use(Session.initMiddleware());

app.use(errorMiddleware);
app.use(authMiddleware);

app.use(router.routes());

app.listen({ port: 7777 });

export default app;

Here is the login controller used in the Router middleware

const loginUser = async ({ request, response, state, cookies }) => {
  const parseBody = await request.body.json();

  const email = parseBody.email;
  const password = parseBody.password;

  const existingUsers = await userService.findUsersWithEmail(email);

  if (existingUsers?.length === 0) {
    response.body = "User not found. Register with the link given below.";
    response.status = 404;
    return;
  }

  const userDB = existingUsers[0];

  const hashedUserDBPassword = userDB.password;

  const matchPasswords = await bcrypt.compare(password, hashedUserDBPassword);
  if (!matchPasswords) {
    response.body = "Incorrect password!";
    response.status = 401;
    return;
  }

  const userLogInDetails = {
    id: userDB.id,
    email: userDB.email,
    admin: userDB.admin,
    isLoggedIn: true,
  };

  await state.session.set("user", userLogInDetails); //This session should be available in every middleware context

  response.status = 200;
  response.body = userLogInDetails;
};

and here is my auth middleware

const authMiddleware = async ({ request, response, state, cookies }, next) => {
  const authRoutes = request.url.pathname.includes("auth");

  const user = await state.session.get("user"); // This is undefined on every route 

  await next();
  return;
};

export { authMiddleware };

The session set in the login controller await state.session.set("user", userLogInDetails); should be available on every subsequent API calls but is always undefined.

What I am missing here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions