npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-app-session

v1.0.7

Published

A Next.js App router server-side session library

Downloads

10,713

Readme

Next-App-Session

npm npm bundle size npm bundle size ts nextjs nextjs

This package is built to work with Next.js v13 App router and Server Components & Actions, additionally it also supports Pages router and middleware.

This Next.js package enables secure storage of sessions in a server side store like express-session or redis or others, the package uses the next.js dynamic function cookies() to store the session id on the client side and that session id is then associated with user data on the server store.

Package was inspired by express-session & next-session.

Setup

  1. Install package in your Next.js project

    npm i next-app-session 
  2. Create an initialisation file, for example: lib/session.ts, and write an exportable session variable like follows:

    import nextAppSession from 'next-app-session';
       
    // Your session data type
    type MySessionData = {
       access_token?: string;
       counter?: number;
    }
       
    // Setup the config for your session and cookie
    export const session = nextAppSession<MySessionData>({
       // Options
       name: 'SID',
       secret: 'secret goes here' ,
       ...
    }); 
  3. You can now use session() or session(req) in your App router & Page router i that order

    App router: Route Handler/Server Components/Server Actions

    await session().get()

    Pages router/middleware:

    await session(req).get() // where req is the IncomingMessage/NextApiRequest object

Note: in App router, session can only read data in Server Components while it can read+write data in Route Handler and Server Actions. It follows the same usage rules as the cookies() dynamic function

A Router handler usage example:

// Example for route handler
import { session } from '../lib/session'; //We import it from the initialisation file we created earlier

// Increment counter
export async function POST(request: Request) {
   // Read counter value froms session
   const current = await session().get('counter');

   //Increment value or assign 1 if no value exists
   const newValue = current ? Number(current) + 1 : 1;

   // Update counter session
   await session().set('counter', newValue);
}

Page router usage example:

// Example for route handler
import { session } from '../lib/session'; //We import it from the initialisation file we created earlier

 // Serve session as props
 export async function getServerSideProps({ req }) {
 	// Get data from session
 	const data = await session(req).all();
 
 	// Pass data to the page via props
 	return { props: { ...data } };
 }

Options

| Property | Description | Default | |:-----------|:----------|:----------| | name | Name of the client cookie that holds the session ID |'sid' | | secret | This is the secret used to sign the session cookie which will hold the user session ID. If left empty the session ID is not signed/encoded | | | store | The session store instance, defaults to a new MemoryStore instance which is for dev purposes only, other production compatible stores can be used, more on how to use them below | new MemoryStore() | | genid | This callback can be used to override the unique session id creation allowing you to set your own, By default nanoid package is used to generate new session IDs | nanoid | | cookie | An object can be passed here to control the configuration of the client cookie | |


Methods

await session().get('key')

This will fetch the session and return the stored property that matches the key passed to it.

await session().all()

This will fetch all session data

await session().set('key', value)

This will set the data with the property key passed

await session().setAll(object)

This will set all session data

Notice: The session set methods work the same way as the next.js cookies dynamic function, it will only work in the context of Route Handlers & Server Actions. while the get methods will additionally work on the Server Components.


Stores

As we mentioned before by default the package will use MemoryStore, which is an express session singleton that lasts until the node process is killed, because of that MemoryStore is not recommended for production use. and instead you should consider using other stores such as Redis or a database service.

How to use a Redis store

  1. First setup a redis instance, for exmaple using docker you can add this to your docker-compose.yml file

    version: '3.8'
    services:
      redis:
        image: redis:latest
        ports:
          - '6379:6379'
  2. Run the docker container, in your terminal naviaget to your project and run:

    docker-compose up
  3. Install redis packages in your project:

    npm i ioredis connect-redis
  4. Update the session config so its like follows with the port you're redis instance is running on:

    import nextAppSession, {promisifyStore} from 'next-app-session';
    import Redis from 'ioredis';
    import RedisStoreFactory from 'connect-redis';
    
    export const session = nextAppSession({
      name: 'EXAMPLE_SID',
      secret: 'secret goes here' ,
      // Assign Redis store with connection details
      store: promisifyStore(
        new RedisStore({
          client: new Redis({
            host: 'localhost',
            port: 6381
          }),
          prefix: 'exampleapp:'
        })
      )
    }); 

Other compatible stores

Any express session store package should be supported as long as they're passed through promisifyStore utility function

Example

a Next.js demo app is located under ./example of this repo.

Contribution

GitHub issues

Feedback, Issue reports, suggestions and contributions are welcome and appreciated.

https://github.com/sweetscript/next-app-session/issues

https://github.com/sweetscript/next-app-session/discussions

[email protected]