Next.js Discord

Discord Forum

help for redirection

Answered
Netherland Dwarf posted this in #help-forum
Open in Discord
Netherland DwarfOP
I hav make a login system and use useSession and useRouter for redirection, how do I make better code for it. Else I'll have to repeat it in all my admin pages.

Code :
"use client";

import { useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import "../../../style/dashboard.css";

const DashboardPage = () => {
  const router = useRouter();
  const { data, status } = useSession();

  useEffect(() => {
    if (status === "loading") {
      return;
    }

    const isAuthenticated = status === "authenticated";
    const isAdmin = data?.user?.role?.toUpperCase() === "ADMIN";

    if (!isAuthenticated || !isAdmin) {
      router.push("/");
    }
  }, [status, data, router]);

  if (status === "loading") {
    return <div>Chargement...</div>;
  }

  return (
    <div>
      <h1>Bienvenue sur le pannel admin {data?.user?.name}.</h1>
    </div>
  );
};

export default DashboardPage;
Answered by B33fb0n3
yes, you can't get the session via the client, because the middleware is serverside. You need to get the session serverside. It's a bit complicated in middleware. You can use the following to get your session:
const session = await getToken({req: request});
View full answer

14 Replies

@Netherland Dwarf solved?
Netherland DwarfOP
I haven't tried it yet, i update this thread after try this
Netherland DwarfOP
Hey @B33fb0n3, I tried with the middleware but I didn't succeed with the role, do you have any idea how I could do it with the role, I want to use the authentication role to access the admin page.
@B33fb0n3 What did not work with the role? You should get the same information as you would clientside…
Netherland DwarfOP
i can't use useSession() for fetch the role the user in middleware. I understand it's possible with cookies you know if it's good practice or if other options it's possible?
@Netherland Dwarf i can't use useSession() for fetch the role the user in middleware. I understand it's possible with cookies you know if it's good practice or if other options it's possible?
yes, you can't get the session via the client, because the middleware is serverside. You need to get the session serverside. It's a bit complicated in middleware. You can use the following to get your session:
const session = await getToken({req: request});
Answer
@B33fb0n3 yes, you can't get the session via the client, because the middleware is serverside. You need to get the session serverside. It's a bit complicated in middleware. You can use the following to get your session: tsx const session = await getToken({req: request});
Netherland DwarfOP
ty for the solution, just one last question, it's possible all page dashboard without the make one by one ?
import { NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";
import { NextApiRequest } from "next";

export async function middleware(request: NextApiRequest) {
  const session = await getToken({ req: request });

  if (!session && request.url === "http://localhost:3000/logout") {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  if (session && request.url === "http://localhost:3000/login") {
    return NextResponse.redirect(new URL("/logout", request.url));
  }

  if (
    session?.role !== "ADMIN" &&
    request.url === "http://localhost:3000/dashboard"
  ) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  return NextResponse.next();
}
yes, set the matcher of the middleware to only be executed for these specific routes. You can also match every route, if you need to. You can see some example here: https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths
Netherland DwarfOP
Ok, thanks for all the replies, I had a different idea.

I not undestand how to run matcher.

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(request: NextRequest) {
  const session = await getToken({ req: request });

  if (!session && request.url === "http://localhost:3000/logout") {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  if (session && request.url === "http://localhost:3000/login") {
    return NextResponse.redirect(new URL("/logout", request.url));
  }

  if (
    session?.role !== "ADMIN" &&
    request.url.startsWith("http://localhost:3000/dashboard")
  ) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  return NextResponse.next();
}
Yea, of course you can also define every route manual. The result is the same 🙂
Netherland DwarfOP
Yeah, ty enjoy your evening !
happy to help