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.
-
Install package in your Next.js project
npm i next-app-session
-
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' , ... });
-
You can now use
session()
orsession(req)
in your App router & Page router i that orderawait session().get()
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 } };
}
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 |
This will fetch the session and return the stored property that matches the key passed to it.
This will fetch all session data
This will set the data with the property key passed
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.
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.
-
First setup a redis instance, for exmaple using docker you can add this to your
docker-compose.yml
fileversion: '3.8' services: redis: image: redis:latest ports: - '6379:6379'
-
Run the docker container, in your terminal naviaget to your project and run:
docker-compose up
-
Install redis packages in your project:
npm i ioredis connect-redis
-
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:' }) ) });
Any express session store package should be supported as long as they're passed through promisifyStore
utility function
a Next.js demo app is located under ./example
of this repo.
Feedback, Issue reports, suggestions and contributions are welcome and appreciated.
https://github.com/sweetscript/next-app-session/issues