DEV Community

Shameel Uddin
Shameel Uddin

Posted on

Next.js 13 | Redirect To Different URL in Server Component vs. in Client Component

I just shifted to Next.js 13 (pretty late in the game, I know) but I faced a little bit issue with re-direction so posting a quick article about it.

Note: Don't be confused about session in the below example. I used next-auth to get the session on root page and based on that, I re-direct a person to either login page or dashboard page.

You can implement this logic as per your own use-case.

TL;DR:

  • Use redirect for Server Side Components.
  • Use useRouter for Client Side Components.

Redirecting To Different URL in Server Component

Use redirect:

import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { redirect } from "next/navigation";

export default async function Home() {
  const session = await getServerSession(authOptions);
  if (session?.accessToken) {
    redirect("/dashboard");
  } else {
    redirect("/login");
  }
}

Enter fullscreen mode Exit fullscreen mode

Read more about redirect here

Redirecting To Different URL in Client Component

Implement useRouter:

"use client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

export default function Home() {
  const router = useRouter();
  const { data: session } = useSession();
  if (session?.accessToken) {
    router.push("/liveTracking");
    return;
  }else{
    router.push("/login");
  }
Enter fullscreen mode Exit fullscreen mode

Read more about useRouter here

One such example I implemented for client side is this:

const handleClick = async () => {
    const { userName, password } = formData;
    const data = await signIn("credentials", {
      userName,
      password,
      redirect: false,
    });
    if (data?.status === 200) {
      router.push("/dashboard");
    }
  };
Enter fullscreen mode Exit fullscreen mode

In this example, I used next-auth to verify credentials in login page and redirected the user to dashboard.

I might be writing about next-auth in future articles as well. This one was mainly for redirecting the user in next.js 13 in server and client side components.

Hope that helps =)

Follow me for more of such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (0)