Next.js - How to Get Session Information in Server Side vs Client Side iusing Next-auth

May 04, 2021

Introduction

Next-auth is a fantastic library for abstracting handling of session information.

In our previous post, we have seen How to Detect user is authenticated or not

In this post, we will see how to use session information in client side vs server side.

Fetching Session Information in Client Side

What is Client Side? Client side means, whatever code is executed on the browser.

First Include the import statements,

import { getSession } from 'next-auth/client'

Get session info,

const session = await getSession();

Now you can fetch any information you have saved in session.

session.jwt
session.user

Fetching Session Information in Server Side

We will run this code in Next.js server side in getServerSideProps

import { getSession } from 'next-auth/client'

export async function getServerSideProps({req}) {
  let headers = {}
  const session = await getSession({ req });
  if (session) {
    headers = {Authorization: `Bearer ${session.jwt}`};
  }
  
  // Use this session information where you want.
}

Similar Posts

Latest Posts