Next.js Discord

Discord Forum

my middleware doesn't let me go to the home page.

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
So basically I made a middleware that check if a user actually registered with their phone number (this is a fake whatsapp).

I already checked if I create a cookie session and if the encrypt and decrypt work which they do, issue is I never get to be able to re-render to the /home route even if I get a cookie session activate which I debugged. My only conclusion is that my updateSession which is a func that update the cookie exp date, the use for it is that if I log in today at x time and let's say cookies expires at 6 days, if I log in 5 days after the login the cookie will be renewed.

this is the middleware:
const protectedRoutes = ["/home"];

export async function middleware(req: NextRequest): Promise<NextResponse> {
  const path = req.nextUrl.pathname;
  const isProtectedRoute = protectedRoutes.includes(path);
  const cookie = (await cookies()).get("session")?.value;
  const session = cookie ? await decryptCookies(cookie) : null;

  if (!session && isProtectedRoute) {
    return NextResponse.redirect(new URL("/", req.nextUrl));
  } else if (session && !isProtectedRoute) {
    return NextResponse.redirect(new URL("/home", req.nextUrl));
  }
  return await updateSession(req);
} 


export async function updateSession(
  request: NextRequest
): Promise<NextResponse> {
  {
    // This function only used for updating the session cookies in the middleware
    // returns a new response to the server
    const session = request.cookies.get("session")?.value!;

    if (!session) {
      return NextResponse.next();
    }
    const parsed = await decryptCookies(session);
    parsed.expires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24h forward

    const res = NextResponse.next();
    res.cookies.set({
      name: "session",
      value: await encryptCookies(parsed),
      expires: parsed.expires,
      httpOnly: true,
    });

    return res;
  }
}

3 Replies

Sun bearOP
This is also my login button logic:
export async function loginUser(
  previousState: any,
  formData: FormData
): Promise<void> {
  const data = Object.fromEntries(formData.entries()) as loginData;

  if (!data.phone) {
    console.error("no formData");
    return;
  }

  try {
    const user = await prisma.user.findFirst({
      where: { phoneNumber: data.phone },
    });

    if (!user)
      await prisma.user.create({
        data: {
          phoneNumber: data.phone,
          usernames: data.phone,
        },
      });

    await createSession(data);

    redirect("/home");
  } catch (error) {
    // error.stack is used because of some bug/glitch with prisma atm of dev
    // @ts-ignore ignore the error from error.stack
    console.log(error.stack);
  }
}
this is a bit simplified because there is no number validation or something like that to check if the user is actually them but after the await createSession I cannot seem to trigger the redirect("/home") for some odd reason everything works except that
Sun bearOP
I solved the issue I needed to redirect outside the try catch block