Skip to content

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

Open

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?

Activity

  1. karolkt1 commented on Mar 21, 2025

    @karolkt1

    I think you might be missing a session store. I've encountered a similar issue before. You can use a library for storing sessions and choose from multiple stores. For example, you can use a CookieStore, where your session info is encrypted and stored in the client's browser.

    import { oakCors } from "https://deno.land/x/cors/mod.ts";
    import { authMiddleware } from "./middlewares/authMiddleware.js";
    import { errorMiddleware } from "./middlewares/errorMiddleware.js";
    import { Session, CookieStore } from "https://deno.land/x/oak_sessions@v9.0.0/mod.ts";
    
    import { router } from "./routes/routes.js";
    
    const app = new Application();
    app.use(
      oakCors({
        origin: "http://localhost:5173",
      }),
    );
    
    const cookieStore = new CookieStore("use-long-random-keys-as-pwd");
    app.use(
      Session.initMiddleware(cookieStore, {
        expireAfterSeconds: 8 * 3600, // 8 hours
        cookieSetOptions: {
          httpOnly: false,
          secure: false,
          sameSite: "lax",
          maxAge: 1000 * 60 * 60 * 24,
        },
        sessionCookieName: "session",
      })
    );
    
    app.use(errorMiddleware);
    app.use(authMiddleware);
    
    app.use(router.routes());
    
    app.listen({ port: 7777 });
    
    export default app;
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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