vvo/iron-session

req.session.user not found on first request on protected page

thomasop opened this issue · 0 comments

Hello, I am experiencing a problem. When I log in, the session is created successfully, and the cookie is also generated. However, when I make the first call to a protected route, such as /profile (protected by middleware), the session is found in the middleware. But when I use req.session.user in the API route, it doesn't work, and req.session returns undefined. However, this only happens on the first call. In fact, when I refresh the same page, /dashboard, it works perfectly.

This is my code :

import { getIronSession } from "iron-session/edge"
import { NextRequest, NextResponse } from "next/server"

export const middleware = async (req: NextRequest) => {
     const res = NextResponse.next()
     const session = await getIronSession(req, res, {
        cookieName: "test",
        password: "tesdfjklsjtesdfjktesdfjklsjdfljslkdfjlsjdflslqfdjkstlsjdfljslkdfjlsjdflslqfdjkstdfljslkdfjlsjdflslqfdjkst",
        cookieOptions: {
            secure: process.env.NODE_ENV === "production"
        }
     })
     const {user} = session
     if (!user) {
        return NextResponse.redirect(new URL('/', req.url))
     }
     if (user.role !== "ROLE_USER") {
        return NextResponse.redirect(new URL('/', req.url))
     }
     return res
}

export const config = {
    matcher: "/profile",
}

and my api route :

import { NextApiResponse } from "next";
import prisma from "../../../lib/prisma";
import { withIronSessionApiRoute } from "iron-session/next";

export default withIronSessionApiRoute(
  async function getUserRole(req: any, res: NextApiResponse) {
    if (req.method === "GET") {
      if (req.session.user) {
        const user = await prisma.user.findUnique({
          where: { id: req.session.user.id },
          include: { meetings: true },
        });
        if (user === null) {
          return res.status(400).json({
            status: 400,
            message: "user not found",
          });
        } else {
          let userObject = {
            id: user.id,
            role: user.role,
          };
          return res.status(200).json({
            status: 200,
            body: userObject,
          });
        }
      }
      return res.status(404).json({
        status: 404,
        body: "user",
      });
    }
  },
  {
    password:
      "tesdfjklsjtesdfjktesdfjklsjdfljslkdfjlsjdflslqfdjkstlsjdfljslkdfjlsjdflslqfdjkstdfljslkdfjlsjdflslqfdjkst",
    cookieName: "test",
    cookieOptions: {
      secure: process.env.NODE_ENV === "production",
    },
  }
);