Sessions in Next js : A Comprehensive Guide

Sessions play an important role in creating dynamic and user intense applications. Sessions enable maintaining user-specific data which can be persisted across requests. In this article, we will discuss various aspects of start using Session in Next js in effective and efficient ways which will enable to creation of production-ready websites to provide industrial-level standards.…

By.

•

min read

Sessions play an important role in creating dynamic and user intense applications. Sessions enable maintaining user-specific data which can be persisted across requests.

In this article, we will discuss various aspects of start using Session in Next js in effective and efficient ways which will enable to creation of production-ready websites to provide industrial-level standards.

 

What Are Sessions?

Sessions are used to store and manage user data on the server side as per requirement during user’s interaction period with applications. They are mainly used to maintain authentication state, shopping carts, and other information like user settings across websites.

In Next js, sessions are implemented by using third-party libraries like express-session or next-iron-session. These libraries provide easy-to-use APIs to handle the complexities of session management.

 

 

How to Work with Sessions in Next.js

Follow these easy-to-follow detailed steps to start integration of Sessions in the Next js application:

Step 1 – Create Next js Application

Step 2 – Install the Next Iron Session Package

Step 3 – Using Sessions with Next Iron Session

Step 4 – Configure Session Options

 

Step 1 – Create Next js Application

First, we will create a new Next js application or you can continue with your existing project. Execute the following command to create a new Next js application:

npx create-next-app my-next-app
cd my-next-app

 

Step 2 – Install the Next Iron Session Package

There are a number of packages available to manage Sessions in Next js likeexpress-session and next-iron-session, but in this example, we will use next-iron-session. Execute following command to install the Next Iron Session package:

npm install next-iron-session

 

Step 3 – Using Sessions with Next Iron Session

Now, we will discuss how to start using next-iron-session to implement sessions in the Next js application. The library we using provides a very easy-to-use API.

First, create utils directory at the Next js application root:

mkdir utils

Then create a file named session.js inside the utils directory:

// utils/session.js
import { withIronSession } from 'next-iron-session';

export default withIronSession(
  async (req, res) => {
    const user = /* Fetch user data from your database */;
    req.session.set('user', user);
    await req.session.save();
    return res.end();
  },
  {
    password: 'your-password',
    cookieName: 'session-name',
    // Other options
  }
);

In the above code, we have defined a session handler by usingnext-iron-session. It stores user data in the session and saves it for future reference.

Now, we will use the session handler in our Next js pages:

// pages/index.js
import { useSession } from 'next-iron-session';
import sessionMiddleware from '../utils/session';

const HomePage = ({ user }) => {
  const [session] = useSession();

  return (
    <div>
      {session ? (
        <p>Hello, {user.name}!</p>
      ) : (
        <p>Please log in</p>
      )}
    </div>
  );
};

export default HomePage;

export const getServerSideProps = sessionMiddleware;

Here we are using useSession to access the session data in our Next.js page. The getServerSideProps function is used to enable the server-side rendering and initialize the session.

 

Step 4 – Configure Session Options

In the session.js file, you can customize various options, such as the password which is used for encryption and the cookieName.

Here is the example session.js file with all possible configuration options with their inline comments:

// utils/session.js
import { withIronSession } from 'next-iron-session';
export default withIronSession(
  async (req, res) => {
    // Session handling logic here
  },
  {
    password: 'my-super-secret-password', // Replace with your strong secret password
    cookieName: 'my-session-cookie', // Replace with your desired cookie name
    cookieOptions: {
      secure: process.env.NODE_ENV === 'production', // Only send the cookie over HTTPS in production
      httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
      sameSite: 'strict', // Enhance security by restricting cross-origin sharing
      path: '/', // Specify the path where the cookie is available
      maxAge: 86400, // Cookie lifespan in seconds (1 day in this example)
    },
    cookieIronOptions: {
      password: 'my-cookie-secret', // Replace with a secure cookie secret
      ttl: 3600, // Cookie expiration in seconds (1 hour in this example)
      cookieName: 'my-session-cookie', // Cookie name (should match the one above)
    },
    ttl: 3600, // Session data expires after 1 hour of inactivity
    storeFactory: () => new MemoryStore(), // Use MemoryStore (default)
    encryptionAlgorithm: 'aes-256-gcm', // Specify the encryption algorithm
    cookieAutoSecure: true, // Automatically set the secure flag for cookies in HTTPS
    cookieSameSite: 'none', // Allow cross-origin cookies (requires secure attribute)
    cookieSecure: false, // Disable the secure attribute for cookies (for development or non-HTTPS)
    cookieMaxAge: 604800000, // Cookie expires in 7 days (7 * 24 * 60 * 60 * 1000 milliseconds)
    checkSessionTimeout: true, // Enable session timeout checks (default)
  }
);

 

How to Share Session Data Between Pages in Next.js

As we have already set up the sessions above, now you can access the session data on any page component by using useSession or getSession methods provided by the library.

// pages/profile.js
import { useSession } from 'next-iron-session';

export default function ProfilePage() {
  const [session, loading] = useSession();

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <p>Welcome, {session.user.name}!</p>
    </div>
  );
}

 

How to Access Session Objects in getServerSideProps or getInitialProps in Next.js

We can easily access the session object in getServerSideProps or getInitialProps by passing the session handler function directly which ensures the session is initialized on the server side before the page is rendered.

// pages/secure-page.js
import sessionMiddleware from '../utils/session';

export default function SecurePage({ user }) {
  // Page content
}

export const getServerSideProps = sessionMiddleware(async (context) => {
  // Access session via context.req.session
  const user = context.req.session.get('user');

  if (!user) {
    // Redirect or handle unauthorized access
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    };
  }

  return {
    props: { user },
  };
});

 

Conclusion

We have successfully implemented the Session in the Next js application We also discussed step by step procedure to create a session.js util file where we can configure the options and discussed various use cases like setup up the session and passing the session objects across pages. We also discussed how to access sessions in the Server side executed hooks.

Do let me know in the comments if you are looking for examples of Session bases Authentication, Migrating Sessions from Server to Client Side and Expiring or Clearing Sessions After Inactivity like features in Next js.

Leave a Reply

Your email address will not be published. Required fields are marked *