getSession

getSession guide for our application.

Overview

The getSession server action allows you to retrieve the current user's session information from the server. This is a key component for authentication in Next.js applications.

// Server action implementation
'use server';

import { cookies } from 'next/headers';
import { verifyJwt } from '@/lib/auth';

export async function getSession() {
  const token = cookies().get('token')?.value;
  
  if (!token) {
    return null;
  }
  
  try {
    const payload = await verifyJwt(token);
    return {
      user: {
        id: payload.sub,
        email: payload.email,
        name: payload.name,
        role: payload.role,
      },
      expires: new Date(payload.exp * 1000),
    };
  } catch (error) {
    // Token is invalid or expired
    cookies().delete('token');
    return null;
  }
}
code

Prerequisites

Before proceeding, ensure you have the following:

  • Node.js installed
  • Basic knowledge of command-line interface (CLI)
  • A code editor (e.g., VSCode)

Installation Steps

  1. Clone the Repository: Clone the repository using the following command:

    git clone https://github.com/your-repo/your-project.git
    
    code
  2. Navigate to the Project Directory: Use the cd command to navigate to your project directory:

    cd your-project
    
    code
  3. Install Dependencies: Install the required dependencies using npm or yarn:

    npm install
    # or
    yarn install
    
    code

Client Usage

Here's an example of how to use the getSession function in a client component:

// Client component with session data
'use client';

import { useEffect, useState } from 'react';
import { getSession } from '@/actions/auth';

export default function ProfilePage() {
  const [session, setSession] = useState(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const fetchSession = async () => {
      const sessionData = await getSession();
      setSession(sessionData);
      setLoading(false);
    };
    
    fetchSession();
  }, []);
  
  if (loading) {
    return <div>Loading...</div>;
  }
  
  if (!session) {
    return <div>Not logged in</div>;
  }
  
  return (
    <div>
      <h1>Welcome, {session.user.name}!</h1>
      <p>Your email: {session.user.email}</p>
      <p>Your role: {session.user.role}</p>
    </div>
  );
}
code

Additional Information

For more details, please refer to our official documentation.

Server Action Implementation

// app/actions/auth.ts
'use server'

import { cookies } from 'next/headers';
import { verify } from 'jsonwebtoken';

interface SessionUser {
  id: string;
  email: string;
  name: string;
  role: string;
}

interface Session {
  user: SessionUser;
  expires: Date;
}

export async function getSession(): Promise<Session | null> {
  const token = cookies().get('token')?.value;
  
  if (!token) {
    return null;
  }
  
  try {
    const secret = process.env.JWT_SECRET;
    
    if (!secret) {
      throw new Error('JWT_SECRET is not defined');
    }
    
    const decoded = verify(token, secret) as {
      sub: string;
      email: string;
      name: string;
      role: string;
      exp: number;
    };
    
    return {
      user: {
        id: decoded.sub,
        email: decoded.email,
        name: decoded.name,
        role: decoded.role,
      },
      expires: new Date(decoded.exp * 1000),
    };
  } catch (error) {
    // Token is invalid or expired
    cookies().delete('token');
    return null;
  }
}
code

Client Component Usage

// app/components/ProfileSection.tsx
'use client'

import { useEffect, useState } from 'react';
import { getSession } from '@/app/actions/auth';

interface SessionData {
  user: {
    id: string;
    email: string;
    name: string;
    role: string;
  };
  expires: Date;
}

export default function ProfileSection() {
  const [session, setSession] = useState<SessionData | null>(null);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    async function fetchSession() {
      try {
        const sessionData = await getSession();
        setSession(sessionData);
      } catch (error) {
        console.error('Failed to fetch session:', error);
      } finally {
        setLoading(false);
      }
    }
    
    fetchSession();
  }, []);
  
  if (loading) {
    return <div className="p-4">Loading...</div>;
  }
  
  if (!session) {
    return <div className="p-4">Please log in to view your profile.</div>;
  }
  
  return (
    <div className="p-4 border rounded-lg bg-card">
      <h2 className="text-xl font-bold mb-4">Your Profile</h2>
      <div className="space-y-2">
        <p><strong>Name:</strong> {session.user.name}</p>
        <p><strong>Email:</strong> {session.user.email}</p>
        <p><strong>Role:</strong> {session.user.role}</p>
        <p className="text-sm text-muted-foreground">
          Session expires: {new Date(session.expires).toLocaleString()}
        </p>
      </div>
    </div>
  );
}
code