#How do i send a cookie from the middleware?

6 messages · Page 1 of 1 (latest)

magic flint
#

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" });
  }
};
unreal kelpBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

magic flint
#

the middleware is not able to send req.session.userId neither can i use relative paths

#

is there a way to fix that

magic flint
#

okk i got that fixed

#

can anyone just tell me