#17 | Sessions & Flashing Messages - AdonisJS 7
Chapters12
This chapter introduces sessions as a way to persist user state across requests, highlighting their role in authentication, preferences, and shopping carts, and notes that a session is created with a unique ID.
AdonisJS 7's session and flash messaging basics are covered with practical examples: how to set a success message in a session, read it on the next page, and switch to flash messages for one-time notifications.
Summary
Adocasts’ #17 episode breaks down how AdonisJS 7 handles user state with sessions and how to migrate to flash messages for one-time alerts. The presenter demonstrates storing a message in a session after creating a new challenge, then retrieving it on the challenges index page to render a success alert. They show how to use session.put and session.get, including default values, and explain that Edge.js can access the session data directly through the request. A key moment is replacing persistent session data with flash messages to avoid stale notifications persisting across unrelated pages. They walk through using session.flash for one-time messages, and demonstrate forgetting a key after rendering, or letting a page render then forgetting it. The starter layout includes a flash alerts partial with autodismiss enabled, which explains why some messages disappear automatically when using flash. The episode also covers reflash as a way to extend flash lifetimes for specific flows, like keeping errors visible on an index page, and cautions against overusing reflashes. Finally, they show how to align flash usage with separate error handling and updates, ensuring a cohesive UX across create and update flows.
Key Takeaways
- Using AdonisJS 7, you can store per-user data across requests with session.put('success', 'Challenge created successfully') and retrieve it later with session.get('success').
- ],
- target_audience
- Essential viewing for AdonisJS 7 developers who want robust, user-friendly notification handling. It clearly distinguishes between persistent sessions and one-off flash messages, with practical code examples that map directly to common CRUD flows.
- topics
- ["AdonisJS 7","Sessions","Flash messages","Edge.js","HTTP context","session.put","session.get","session.flash","session.forget","reflash"]
Who Is This For?
Essential viewing for AdonisJS 7 developers who want robust, user-friendly notification handling. It clearly distinguishes between persistent sessions and one-off flash messages, with practical code examples that map directly to common CRUD flows.
Notable Quotes
"Sessions are a temporary data storage mechanism that allows your application to maintain state across multiple requests for a specific user."
—Defines the purpose of sessions in AdonisJS.
"Flash messages are a special type of session data in that they only last for one single request."
—Highlights the key difference between session and flash.
"Flash makes your one-time notifications reliable for the next request and then forgets them automatically."
—Explains how flash messaging works in practice.
"If you were to do session.flash, the data is automatically forgotten on the next request."
—Demonstrates the usage of flash in practice.
"Reflash persists any of the flash messages for one more request."
—Shows how to extend flash lifetimes when needed.
Questions This Video Answers
- How do I implement flash messages in AdonisJS 7?
- What is the difference between session.put and session.flash in AdonisJS?
- How does the reflash feature work in AdonisJS flash messaging?
- Why would I prefer flash messages over persistent session data in AdonisJS 7?
AdonisJS 7SessionsFlash messagesEdge.jsHTTP contextsession.putsession.getsession.flashsession.forgetreflash
Full Transcript
So, we have touched on them briefly, but let's go ahead and talk about them in depth. Sessions are a temporary data storage mechanism that allows your application to maintain state across multiple requests for a specific user. They're essential for features like authentication, user preferences, and even shopping carts. When a user first visits your site, Adonjs creates a session for them and stores a session ID inside of a cookie on subsequent requests. then the browser will send that cookie allowing Adonjs to retrieve the session data associated with that specific user. Sessions themselves are ephemeral by default.
They exist for the duration of the user's visit and can be cleared out whenever the browser closes depending on your configuration. If we jump up to our store method here, whenever our user creates a brand new challenge, let's say that we want to inform them that their challenge was successfully created whenever we redirect them back to our challenges index page. sessions enable this functionality for us by allowing us to set something on our session here with that message directly inside of our store route handler that will then be persisted beyond our redirection to our challenges index page for use.
So we can plug our session out of our HTTP context and add something to it using the session put method. We can provide this a key. So since we want to display a success message, we can call the key success there and then it allows a value as well. This could be an object or a simple primitive for here. Let's just set a simple primitive of a string. Challenge created successfully. Once we've set something on our session, it can then be used throughout our requests life cycle. So, if we scroll now up to our index method, which is where we're redirecting to, and we pluck our session out of here, we can get at it by doing const success message equals session dot and use the get method to get a specific key out of our session data.
And again, you'll notice similar to other methods like get here, we can provide a default value if the key that we're after doesn't exist in the user session. So, we can check to see whether or not we have a success in there with this. And if it's in there, provide it into our render state via success message just like so. Now, similar to the route builder, we actually don't need to generate this inside of our controller and pass it through to render state to access it inside of edge.js. We have access to the session as a readonly data store inside of edge.js directly for the request as well.
So, we can get rid of all of that and jump directly inside of our challenges index page. And above our hero div, we can use our sessions readonly store by using an if check if the session and there is also a has method that merely checks to see if the key that we're after exists in the user session store returning back a boolean. So if we have a success key inside of our session data for our user, we can show a div with a class alerts and alert success and then use interpolation to get at that readonly store again for our individual success message.
So with all that saved, if we go ahead and jump back into our browser here and we create a brand new challenge. So we'll just call this test. It doesn't really matter what we call it. And hit enter to create it. Oh, right. Validation testing. There we go. And hit enter to create it. There we go. We get redirected back and we now have our challenge created successfully session message showing up here. Whenever we hit our store endpoint, we added this message to this user session and then we're reading from it whenever we're at our challenges index page as that page is being rendered.
Now, there is an issue with what we just did. So, if we go ahead and refresh this page, our message is stuck to the user session. There's nothing in here clearing it out. It's going to be in here for the duration of our session. So if we go do other things, edit a challenge, visit other pages, this message is still going to be sticky to here, signaling that we have just created a challenge when in fact we did not. We created it several requests ago. This is where flash messages enter into the picture. Flash messages are a special type of session data in that they only last for one single request.
This makes them perfect for our one-time notifications like what we've just done. Unlike session.put, put where the data persists for the duration of the session until manually deleted or the session expires. When we use session.flash, the data is automatically forgotten on the next request. So our first step, we need to clear our success message out of our session. Otherwise, it's just going to be persisted in there. So jumping back into our challenges controller, then we can go ahead and pluck our session off of our HTTP context one more time. And we can easily forget something from the user session by using the forget method.
And this just accepts in the key that we want to forget there. As an alternative to flash messages that we'll take a look at next, you can also render the page first and then forget a key and then return your response back. So rather than returning directly here, we can actually plop the contents of our HTML into a variable just like so. And then return it after we forget, giving us a similar behavior to our flash message. It will allow us to use the item off of our session one time and then forget it after the render.
So, if we actually gave this a save, jump back into our browser, refresh one more time, we should get our message, but now it should be forgotten after the individual render. So, if we come back into here and refresh one more time, there it goes. It's no longer shown because it's been forgotten. So, that's the similar behavior that we're going to see with flash messaging. So, we can get rid of that forgot altogether. Switch this back to a return and get rid of the return there. And also get rid of our session out of our HTTP context by simply switching our put to a flash call.
And this will do all of that automatically for us regardless of what page we visit next. So the page doesn't need to know about the existence of the flash message itself in this one simple package. So if we now give this a save, jump back into our browser and let's create another new challenge. So we'll call this testing. Give it some point value. Hit enter to create. There we go. We're redirected back. And we now have our success message showing up here. But it looked different that time and it auto hit itself. So why was that?
Well, if you recall back to whenever we were talking about validation in flash messaging, that flash works the exact same way. It's going to add the data to that exact same data store. Meaning that we no longer access it as we did inside of our index page with session has and session get, but rather we access it via flash messages has and flash messages get. So, if we were using something different here, why did it still show and why did it look different and why did it autohide? A lot of questions there. Well, within our layout.
So, if we go into our components layout.edge, you'll notice that there's this partials flash alerts. This came with the starter kit inside of this layout file, and we can commandclick into this partial to see that we actually already have a flash container div here, checking for a flash message with the key of error and a flash message with the key of success, showing an alert for each of those as applicable. And off of our alert route, you'll notice that there is an autod dismissed flag right there set to true, noting why this auto dismissed itself or removed itself from our page.
So this is why we still saw a flash message despite reading from the wrong store inside of our index page of our challenges. With this now switched to our flash messages, if we were to go ahead and create another new challenge, I'm just going to go ahead and call this testing uh whatever I entered there one more time because it doesn't really matter. We'll hit enter. You'll notice that we now get two success messages. one from our page and one from that flash alerts partial. If we refresh one more time, since we use flash messaging rather than setting it directly on the session, it has forgotten about itself and is no longer shown.
Okay, so jumping back into our page then since we already have a partial taking care of this for us, we can go ahead and just remove that al together. And if we wanted a message to match the creation for our update as well, we can do that too within our update handler. So, we'll just import the session and do session flash. Add in a success. Your challenge has been updated. And boom. Now, we have a flash message for both successful creation and updates. Before we move on though, one small final note. You may find yourself in a situation where you need to keep your flash messages for one more request.
Uh, this can be easily done using the reflash message off of our session. So there's a reflash, reflash accept, and reflash only. Now, this doesn't make a whole lot of sense to use right after flashing. Instead, this makes sense on something like our index page, which is what we're redirecting to after creation, since this is where the flash message is forgotten. So, if we were to do session here, with this added, we're instructing it to persist any of the flash messages for one more request. So, if we save that and jump back into our page and create one more new challenge, again, doesn't really matter what this is called.
Hit enter to create that. We have our flash message showing right here. If we let that go away, since we're reflashing on our index page, though, if we reload, we're actually going to get that same flash message back because it's being instructed to persist inside of that flash message store. Since it's still inside of our index page, it's been reflashed yet again. So, if we refresh one more time, there it is. and it's just going to perpetually be there for us since we're reflashing it every time. This reflashing can be particularly handy whenever handling errors manually.
In our particular case though, we don't need that at all right here. So we can go ahead and get rid of it and move onward.
More from Adocasts
Get daily recaps from
Adocasts
AI-powered summaries delivered to your inbox. Save hours every week while staying fully informed.



