#Guys help me how can i acheive protected routes in Nextjs ?
19 messages · Page 1 of 1 (latest)
@dreamy plover so i have cookies which is being sent from backend and i tried using middleware but i am having problems
what have you tried with the middlewares?
@weary ore i created a middleware file
and did this
import { NextResponse } from "next/server";
export default function middleware(req) {
let verify = req.cookies.get("Authorization");
let url = req.url;
if (!verify && url.includes("/dashboard")) {
return NextResponse.redirect("/login");
}
}
what's wrong with it?
Error: URL is malformed "/login". Please use only absolute URLs
@weary ore it seems i found a way to solve this problem
yeah as the error says you can't use relative urls
i need to use return NextResponse.redirect("http://localhost:3000/login") instead of return NextResponse.redirect("/login");
that won't work with the deployed project tho, localhost is only for dev
you can write a new url with new URL('/login', req.url)
notice it takes the current request url with req.url and returns a new url with a different pathname of your choice
yep