Mrutunjay Pradhan
Mrutunjay Pradhan

Reputation: 11

How to extract session in next.js

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body >
        <SessionProvider >
        <Toaster/>
        <RegisterModal/>
        <LoginModal/>
        <Layouts>
        {children}
        </Layouts>
        </SessionProvider>
        </body>
    </html>

Help me to extract sessions so that I can pass it to the <SessionProvider> , I don't know how to extract the session object. I can have only children.

Upvotes: 1

Views: 63

Answers (2)

Hein Soe
Hein Soe

Reputation: 53

layout

//import getSession()
export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const session = await getSession();
  return (
    <html lang="en">
      <body >
        <SessionProvider session={session}>
        <Toaster/>
        <RegisterModal/>
        <LoginModal/>
        <Layouts>
        {children}
        </Layouts>
        </SessionProvider>
        </body>
    </html>

context

// SessionContext.tsx
"use client";
import React, { createContext, useContext, ReactNode, useState } from "react";

interface SessionContextType {
  session: any;
}

const SessionContext = createContext<SessionContextType | undefined>(undefined);

interface SessionProviderProps {
  session: any;
  children: ReactNode;
}

const SessionProvider: React.FC<SessionProviderProps> = ({ session, children }: SessionProviderProps) => {
  
  return (
    <SessionContext.Provider value={{ session }}>
      {children}
    </SessionContext.Provider>
  );
};

export const useSession = (): SessionContextType => {
  const context = useContext(SessionContext);
  if (!context) {
    throw new Error("useSession must be used within a SessionProvider");
  }
  return context;
};

export default SessionProvider;

use in client component

const {session} = useSession() 

Upvotes: 0

Hein Soe
Hein Soe

Reputation: 53

make a function;

"use server";
import { cookies } from "next/headers";
export async function getSession() {
  const session = cookies().get("session")?.value;
  if (!session) return null;
  
  return session;
}

use

//import getSession()
export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const session = await getSession();
  return (
    <html lang="en">
      <body >
        <SessionProvider >
        <Toaster/>
        <RegisterModal/>
        <LoginModal/>
        <Layouts>
        {children}
        </Layouts>
        </SessionProvider>
        </body>
    </html>

Upvotes: 0

Related Questions