How can I correctly route?
Answered
Glen of Imaal Terrier posted this in #help-forum
Glen of Imaal TerrierOP
I check for tokens. If no token found, I route to the login page. The issue is that I route to the login page using useRouter which only works in client component. This leaves all my pages as client component which apart from the use of useRouter is unnecessary. The alternative is to make the layout a client component but this is a bad practice. How do I go about this or do I just accept that if i'm checking for a token on a page and I redirect if none is found then my pages must be client. If something other than use router works and my pages can stay as server components, I'm happy to try that.
samples
samples
"use client";
import { Form } from "./components/Form";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
export default function CreateProfile() {
const router = useRouter();
const cookie = Cookies.get("token");
if (!cookie) {
router.push("/login");
return;
}
return (
<div className="pt-5">
<Form />
</div>
);
}
"use client";
import { DashboardDetails } from "./dashboard/components/DashboardDetails";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
export default function Profile() {
const cookie = Cookies.get("token");
const router = useRouter();
if (!cookie) {
router.push("./login");
return;
}
return (
<>
<DashboardDetails />
</>
);
}
7 Replies
I think you should use middleware
Glen of Imaal TerrierOP
Can you explain more what you mean?
You want to restrict access to dashboard page if he is not logged right?
It's what I figured out by your message/code.
It's what I figured out by your message/code.
Glen of Imaal TerrierOP
I restrict access if not logged in yes. Then I redirect to the login page
Answer
If there is cookie then use
NextResponose.next
, else NextRespnose.redirect
.Glen of Imaal TerrierOP
This looks correct. I'll look into it and attempt implementation