#Guys help me how can i acheive protected routes in Nextjs ?

19 messages · Page 1 of 1 (latest)

smoky python
#

welppppp

dreamy plover
#

wdym by protected route?

#

you can use jwt or middleware and next auth

smoky python
#

@dreamy plover so i have cookies which is being sent from backend and i tried using middleware but i am having problems

weary ore
#

what have you tried with the middlewares?

smoky python
#

@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");
}
}

weary ore
#

what's wrong with it?

smoky python
#

Error: URL is malformed "/login". Please use only absolute URLs

#

@weary ore it seems i found a way to solve this problem

weary ore
#

yeah as the error says you can't use relative urls

smoky python
weary ore
#

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

smoky python
#

ohh so will it also work when i have other urls?

#

i mean with the deployed project?

weary ore
#

yep