Why am i getting this url parse error
Answered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Schneider’s Smooth-fronted CaimanOP
import { NextResponse } from "next/server";
export async function middleware(request: Request) {
const data = await fetch("/api/auth/checkAuth");
const res = await data.json();
if (res.exists) {
NextResponse.next();
}
console.log("Not logged in");
}this is my authroute in the backend
export const checkAuth = async (req, res) => {
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" });
}
};Answered by Schneider’s Smooth-fronted Caiman
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: ["/"],
};okk now it works
3 Replies
Schneider’s Smooth-fronted CaimanOP
okk using absolute paths work
is there a way i can use relative paths tho?
import { NextResponse } from "next/server";
export async function middleware(request: Request) {
const res = await fetch("http://localhost:5000/api/auth/checkAuth");
const data = await res.json();
if (data.exists === true) {
console.log(data.exists);
return NextResponse.next();
}
console.log("Not logged in");
return NextResponse.redirect("http://localhost:3000/");
}is there a way i can use relative paths tho?
also why isnt it loading
Schneider’s Smooth-fronted CaimanOP
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: ["/"],
};okk now it works
Answer