Search code examples
node.jssessionnext.jsserver-side-rendering

Nextjs next-session storage other than memory


I don’t find any resource or package to use another storage other than memory for next-session, where memory is not a suitable solution for production?

I want to use either file storage ( preferred ) or db .


Solution

  • you can store session for example in sqlite3.

    1. install sqlite 'npm install connect-sqlite3'
    2. Create a new file for example 'get-session.js' and write this:
    import nextSession from "next-session";
    import { expressSession, promisifyStore } from "next-session/lib/compat";
    var SQLiteStore = require("connect-sqlite3")(expressSession);
    
    export const getSession = nextSession({
      name: "WIB_SESSION",
      store: promisifyStore(
        new SQLiteStore({ dir: "./tmp/", table: "wiberSessions" })
      ),
    });
    
    1. Create a new api endpoint and put this.
    import { getSession } from "../../lib/get-session.js";
    export default async function handler(req, res) {
      const session = await getSession(req, res);
      const data={hello:"hello im a data in session"}
      session.myData= data
    
      res.status(200).json({save:"session saved"});
    }
    export const config = {
      api: {
        externalResolver: true,
      },
    };
    
    1. And now from your Page
    import { getSession } from "../lib/get-session";
    
    export async function getServerSideProps({ req, res }) {
      const session = await getSession(req, res);
    
      return {
        props: {
          dataInSession: session.myData,
    
        },
      };
    }
    

    Now you will have a cookie named "WIB_SESSION" with a value, and the data stored in a database SQLITE in ./tmp/wiberSessions.

    Here you have a basic project with next. Github

    First time you load the page, First Time And when you press the button and reload the page you have the cooki and the value from the /tmp/sqlite.withcookie

    Greetings