In this article, we can try to Install and Configure the Session package, how to install and configure the Session package for AdonisJS, Config the Session package, and configure the Session package and Usage.
Session
Firstly, the support for sessions is provided by the @adonisjs/session package. This Session package comes pre-configured with the web starter template.
However, installing and configuring the Session is also relatively straightforward.
Install
npm i @adonisjs/session
You can check our previous article: AdonisJS: REST API simple CRUD Operation. IF you want then buy a good, reliable, secure web hosting service from here: click here
Configure
node ace configure @adonisjs/session # CREATE: config/session.ts # UPDATE: .env { "SESSION_DRIVER = cookie" } # UPDATE: .adonisrc.json { providers += "@adonisjs/session" }
Validate environment variables
/** * Make sure to add the following validation rules to the * `env.ts` file to validate the environment variables. */ export default Env.rules({ // ...existing rules SESSION_DRIVER: Env.schema.string(), })
Session Configuration
So, you can configure the behavior of the session by tweaking the config/session.ts file for your project. Following below is the default config file.
import { sessionConfig } from '@adonisjs/session/build/config' export default sessionConfig({ enabled: true, driver: Env.get('SESSION_DRIVER'), cookieName: 'adonis-session', clearWithBrowser: false, age: '2h', cookie: {}, // see the cookie driver file: {}, // see the file driver redisConnection: 'local', // see the redis driver })
Session Drivers
And the session package allows you to choose between one of the available drivers to save the session data on your own projects.
So, you can configure the driver inside the config/session.ts file and the driver property, in turn, relies on the SESSION_DRIVER environment variable.
{ driver: Env.get('SESSION_DRIVER'), }
Cookie Driver
Hence the cookie driver also works great even when your application or project is behind a load balancer since it will no information is stored on the server.
So, you can pinch the settings for the cookie driver inside the config/session.ts file.
{ /* |--------------------------------------------------------------- | Cookies config |--------------------------------------------------------------- | | The cookie settings are used to set up the session id cookie | and also the driver will use the same values. | */ cookie: { path: '/', httpOnly: true, sameSite: false, }, }
File driver
Therefore, the file driver stores the session data on the server filesystem and you can configure the storage location by updating the value of the file.location property inside the config/session.ts file for your application or project.
{ file: { location: Application.tmp('sessions'), }, }
Redis
Now, the configuration for the redis driver references one of the pre-defined redis connections inside the config/redis.ts file in your projects.
You can purchase your hosting from Cloudsurph.com, Cloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.
{ driver: 'redis', redisConnection: 'local', }
Next, you can define a connection named local inside the config/redis.ts file to your project.
{ connections: { local: { host: Env.get('REDIS_HOST'), port: Env.get('REDIS_PORT'), password: Env.get('REDIS_PASSWORD', ''), db: 0, } } }
Read/Write session values
So, you can interact with sessions by using the ctx.session property.
Route.get('/', async ({ session }) => { // Read value const cartTotal = session.get('cart_total') // Write value session.put('cart_total', cartTotal + 10) })
After then, here read-only version of the session is also available inside the Edge templates and you can access it using the session global helper.
<p> Cart total: {{ session.get('cart_total', 0) }} </p>
get
After, read the value for a given key from the session store. Because you can define a default value to return when the actual value is undefined or null.
session.get('cart_total') session.get('cart_total', 0)
put
Now, write a key-value pair to the session store for the value should be one of the cookie-supported data types.
session.put('cart_total', 1900)
all
Now, read everything from the session store and you Will always be an object of a key-value pair.
console.log(session.all())
forget
Now remove the value for a given key from the session store.
// Remove session.forget('cart_total') session.get('cart_total') // undefined
increment
Now, Increment the value for a given key and Make sure the original value is always a number. The Calling increment on a non-numeric value will result in an exception.
session.increment('page_views')
decrement
But, Decrement the value for a given key and Make sure the original value is always a number. The Calling decrement on a non-numeric value will result in an exception.
session.decrement('score')
clear
This is Clear the session store to an empty state.
You can purchase your hosting from Cloudsurph.com, Cloudsurph hosting is a reliable hosting option for business and personal projects. We offer insight and help on system configuration issues and code errors or bugs.
session.clear()
Session id lifecycle
Firstly, AdonisJS creates an empty session store and assigns it to a unique and separate session id on the first HTTP request, also even if the request/response lifecycle doesn’t interact with sessions.
console.log(session.sessionId) if (!session.initiated) { await session.initiate(false) } if (!session.fresh) { session.regenerate() } session.regenerate()
Session flash messages
Secondly, Flash messages are stored inside the session store and are only available for the next HTTP request. Here you can use them for passing messages between HTTP requests. Check the given example below:
Route.get('/', async ({ session, response }) => { session.flash('message', 'Hello world') response.redirect('/see-message') }) Route.get('/see-message', async ({ session }) => { return session.flashMessages.get('message') })
Here we can use some methods like flash, flashAll, flashOnly, flashExcept, reflash, reflashOnly, reflashExcept, and Accessing flash messages, we will discuss another article. Finally, if you need to know more about this topic then please go to the AdonisJS main website.
If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.