Next.js Discord

Discord Forum

How do i send a cookie from the middleware?

Unanswered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Open in Discord
Schneider’s Smooth-fronted CaimanOP
this is my middleware
import { NextResponse } from "next/server";

export async function middleware(request: Request) {
  const authUrl = "http://localhost:5000/api/auth/checkAuth";

  try {
    const res = await fetch(authUrl);

    const data = await res.json();
    console.log(data);

    if (data.exists === true) {
      console.log(data.exists);
      return NextResponse.next();
    }
    return NextResponse.redirect(new URL("/login", request.url));
  } catch (err) {
    console.log(err);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}

export const config = {
  matcher: ["/"],
};

and this is my route in my express server
export const checkAuth = async (req, res) => {
  console.log(req.session.userId);
  if (!req.session.userId) {
    return res.status(400).json({ error: "You are not logged in" });
  }

  try {
    const user = await User.findById(req.session.userId);
    if (user) {
      return res.json({ exists: true, user });
    } else {
      return res.json({ exists: false });
    }
  } catch (err) {
    return res
      .status(500)
      .json({ error: "An error occurred while checking the user" });
  }
};

5 Replies

Schneider’s Smooth-fronted CaimanOP
the middleware is not able to send req.session.userId neither can i use relative paths
is there a way to fix that
Schneider’s Smooth-fronted CaimanOP
okk i got that fixed
can anyone just tell me
import { NextResponse, NextRequest } from "next/server";

export async function middleware(request: NextRequest) {
  const authUrl = "http://localhost:5000/api/auth/checkAuth";

  try {
    const res = await fetch(authUrl, {
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        Cookie: request.headers.get("cookie") || "",
      },
    });

    const data = await res.json();

    if (data.exists === true) {
      console.log(request.url);
      if (request.url.startsWith("/login") || request.url.startsWith("/signup")) {
        return NextResponse.redirect("/");
      }
    }

    if (!data.exists) {
      if (request.url.startsWith("/")) {
        return NextResponse.redirect("/login");
      }
    }
  } catch (err) {
    console.error("Error during authentication check:", err);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}

export const config = {
  matcher: ["/", "/login"],
};

here the value of request.url is http://localhost:3000/login
is there any method i can use to check the base url + route cuz i cant direclty place the absolue rul