Next.js Discord

Discord Forum

Middleware help

Unanswered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Open in Discord
Schneider’s Smooth-fronted CaimanOP
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) {
      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 when i go to http://localhost:3000/login and console.log(request.url.startsWith("/login") it returns false everytime

32 Replies

Schneider’s Smooth-fronted CaimanOP
@Schneider’s Smooth-fronted Caiman Click to see attachment
Black carp
Obviously it will give false
request.url is not path… it is starting with https and your condition is start with /
Use request.nextUrl.pathname
Schneider’s Smooth-fronted CaimanOP
    if (data.exists === true) {
      if (
        request.nextUrl.pathname === "/login" ||
        request.url.startsWith("/signup")
      ) {
        return NextResponse.redirect("/");
      }
    }
like this
Black carp
Dont use request.url anywhere
Because it gives complete url
Schneider’s Smooth-fronted CaimanOP
yes but this is an or operation
both of them are coming to be false
no wait
its working but not really
Black carp
Like i said in ur middleware file
Firstly replace request.url woth request.nexturl.pathname
Then u check what other thing is wrong
Schneider’s Smooth-fronted CaimanOP
yes it works but it gives an error to use absolute path
Black carp
Ya
Use just the path
Schneider’s Smooth-fronted CaimanOP
that what im using
Black carp
Redirect to /api/auth whatever
Schneider’s Smooth-fronted CaimanOP
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();

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

    if (!data.exists) {
      if (request.nextUrl.pathname === "/") {
        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"],
};
@Black carp Redirect to /api/auth whatever
Schneider’s Smooth-fronted CaimanOP
but my complete path is
localhost:3000/login only
@Black carp Redirect to /api/auth whatever
Schneider’s Smooth-fronted CaimanOP
this a request i send to my express backend to check the server session
Black carp
Where the error coming from
Nextresponse.redirect ?
Schneider’s Smooth-fronted CaimanOP
Nextjs itself
Black carp
Check ur terminal
Schneider’s Smooth-fronted CaimanOP
Wait maybe it's next response.redirevt let me uss absolute path
Black carp
Try this

return NextResponse.redirect(new URL('/', request.url))
Schneider’s Smooth-fronted CaimanOP
return NextResponse.redirect("http://localhost:3000/");
works like this
@Black carp Try this return NextResponse.redirect(new URL('/', request.url))
Schneider’s Smooth-fronted CaimanOP
oh
WORKED
TYSM
Black carp
👍