Sajjad Hadi
Sajjad Hadi

Reputation: 11

Server Side Rendering with Auth Package in Next.js

I'm struggling with a question. In Next.js 14 when we are using Auth.js (Next-Auth) package we need to add <SessionProvider> around the element to access the status and data. But SessionProvder must be in a client side component. So we Create a seperate component then we make it client side and finally we can wrap it around the entire application (I've specified and example). But Here is a problem. I think we lost the SSR feature in the app since all the components are the children of a client side component. Is it true? If not what's happening behind the scene?

Layout.tsx

import "@radix-ui/themes/styles.css";
import "./globals.css";
import "./theme-config.css";

import type { Metadata } from "next";
import { Roboto } from "next/font/google";
import { Container, Theme } from "@radix-ui/themes";
import { ReactNode } from "react";
import Navbar from "@/app/components/Navbar";
import AuthProvider from "@/app/components/AuthProvider";

const roboto = Roboto({
  weight: ["400", "700"],
  style: ["normal", "italic"],
  subsets: ["latin"],
  display: "swap",
  variable: "--font-roboto"
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app"
};

export default function RootLayout({ children }: {
  children: ReactNode
}) {
  return (
    <html lang="en" className={roboto.variable}>
      <AuthProvider>
        <body>
          <Theme appearance="light" accentColor="violet">
            <Navbar/>
            <main className="p-5">
              <Container>
                {children}
              </Container>
            </main>
            {/*<ThemePanel/>*/}
          </Theme>
        </body>
      </AuthProvider>
    </html>
  );
}

AuthProvider (SessionProvider):

"use client";

import { PropsWithChildren } from "react";
import { SessionProvider } from "next-auth/react";

const AuthProvider = ({ children }: PropsWithChildren) => {
  return (
    <SessionProvider>{children}</SessionProvider>
  );
};

export default AuthProvider;

I think there are only 2 scenarios:

  1. The children are rendered in the server and the Provider will render in the client (Maybe since it is a context provider)
  2. The whole application becomes client side (which is strange!)

Upvotes: 1

Views: 479

Answers (1)

grekier
grekier

Reputation: 3726

This is not exactly true. The client bundle would contain js for (almost) the whole application but SSR should not really be affected. That being said, you probably don't need the <SessionProvider> as you can do most things without it. Check https://medium.com/@geoffreyrekier/getting-started-with-nextauth-in-server-components-app-router-d1985fece03f which might give you an idea on how to work around it.

Upvotes: 1

Related Questions