{"id":928,"date":"2026-11-21T08:15:28","date_gmt":"2026-11-21T00:15:28","guid":{"rendered":"http:\/\/www.thietkewebbmt.com\/blog\/?p=928"},"modified":"2026-11-21T08:15:28","modified_gmt":"2026-11-21T00:15:28","slug":"how-to-use-session-in-a-controller-4679-0d31b7","status":"publish","type":"post","link":"http:\/\/www.thietkewebbmt.com\/blog\/2026\/11\/21\/how-to-use-session-in-a-controller-4679-0d31b7\/","title":{"rendered":"How to use session in a controller?"},"content":{"rendered":"<p>Hey everyone, let\u2019s cut to the chase\u2014if you\u2019re a software dev, building a custom ERP, e-commerce platform, or even a tiny membership tool, you\u2019ve definitely run into that \u201cwhere do I stash user-specific stuff that needs to stick around between page loads?\u201d problem. Like, a user\u2019s cart items, their login status, maybe that obscure preference for dark mode that they toggled 5 minutes ago but vanished when they clicked the next link. That\u2019s where sessions come in, and as someone who\u2019s been building high-performance controllers (yep, the kind that power the core of your app\u2019s logic) for years, I\u2019ve learned that using sessions in your controller isn\u2019t rocket science\u2014it\u2019s just knowing the right moves that don\u2019t blow up your app. <a href=\"https:\/\/www.busbarwelder.com\/welding-accessory\/controller\/\">Controller<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.busbarwelder.com\/uploads\/44188\/small\/car-seat-frame-welding-machine279d7.png\"><\/p>\n<p>First off, let\u2019s get one thing straight: a lot of new devs mix up sessions and cookies, and that\u2019s a rookie mistake. Cookies are tiny bits of data stored <em>on the user\u2019s browser<\/em>\u2014you can only store like 4KB, and users can block \u2019em or edit \u2019em if they\u2019re sneaky. Sessions? They\u2019re stored <em>on your server<\/em>, and the only thing sent to the browser is a little session ID string. That means you can store way more stuff, it\u2019s way more secure, and users don\u2019t even notice it. For my controller work, this is non-negotiable\u2014sessions let me keep user data private without cramming it into a browser cookie. Now, how do you actually implement this in your controller? Let\u2019s walk through it step by step, no fancy jargon, just real-world stuff I use every day.<\/p>\n<p>Let\u2019s start with the basics: every major framework out there has session support baked in, right? Like Rails has <code>session<\/code>, Express has <code>req.session<\/code>, Django has <code>request.session<\/code>. I\u2019m not here to push one framework over another, but what I <em>will<\/em> say is this: your controller is the middleman between the user\u2019s request and your database, so sessions live here, not somewhere random like your view. That\u2019s key\u2014too many devs stick session code in views and it turns into a mess. Let\u2019s take an example with Express first, since it\u2019s super common for small to mid-sized apps, then hit a Rails example too, just to cover bases.<\/p>\n<p>When you set up your controller, the first thing you need is session middleware. Wait, \u201cmiddleware\u201d sounds fancy, but it\u2019s just code that runs <em>before<\/em> your controller does its thing. For Express, you\u2019ll install <code>express-session<\/code> and plug it into your app like this: <code>app.use(session({ secret: 'yoursecretkeyhere', resave: false, saveUninitialized: false }));<\/code> Let me break that down: the <code>secret<\/code> is a string used to sign the session ID cookie so no one can tamper with it (don\u2019t use a placeholder here\u2014use a long, random string, I use a passphrase I change every 6 months). <code>resave: false<\/code> just means you don\u2019t save the session to the server if nothing changed, and <code>saveUninitialized: false<\/code> means you don\u2019t create a blank session for every single visitor\u2014cuts down on server bloat. As a controller vendor, I always tell my clients this: you don\u2019t need a new session for every random visitor, only people who actually do something, that\u2019s a huge win for performance.<\/p>\n<p>Now, once that middleware is set up, your controller can access the session via <code>req.session<\/code>. Let\u2019s say you\u2019re building an e-commerce cart controller. When a user clicks \u201cAdd to Cart\u201d, your controller action (like <code>\/cart\/add<\/code>) needs to stash that product ID in their session. Here\u2019s how that looks: when a POST request hits <code>\/cart\/add<\/code> with the product ID, your controller does something like this:<\/p>\n<p>First, check if the cart exists in the session. If not, create it. Then add the product. So code-wise:<\/p>\n<p>app.post(&#8216;\/cart\/add&#8217;, (req, res) =&gt; {<br \/>\n\/\/ No cart yet? Make an empty array<br \/>\nif (!req.session.cart) req.session.cart = [];<br \/>\n\/\/ Add the product ID to the cart<br \/>\nreq.session.cart.push(req.body.productId);<br \/>\n\/\/ Send back a response, like redirect to cart page<br \/>\nres.redirect(&#8216;\/cart&#8217;);<br \/>\n});<\/p>\n<p>That\u2019s it? Yeah, basically. The session is tied to the user\u2019s session ID, so every time they make a new request (like going to <code>\/cart<\/code>), the controller checks their session, pulls out that cart array, and displays it. No need to hit the database every time a user adds an item\u2014you only hit the DB when they check out, which is way more efficient. As someone who builds controllers that handle thousands of requests per minute, this is a huge performance hack. Stashing transient user data in the session, not the DB, keeps your app fast.<\/p>\n<p>Now, let\u2019s talk about common mistakes I see devs making with sessions in controllers, because even the above can go wrong if you mess up. First one: storing too much data in the session. Wait, the session is on your server, but if you store like 1MB of user data per session, that\u2019s a problem when you have 10,000 active users. Your controller should only store <em>small, transient<\/em> stuff in sessions\u2014cart items, login user IDs, preferences, that kind of thing. Never store full product records or user profiles in sessions. Instead, store a reference (like a user ID) and pull the full data from the DB when you need it. That\u2019s a rule I enforce with every controller I build\u2014we cap session size at 4KB max, because anything bigger is just wasted server resources.<\/p>\n<p>Second mistake: not setting session expiration. Sessions shouldn\u2019t last forever, right? If a user closes their browser, their session should go away after an hour or so, not stay around for months. In Express, that\u2019s easy to set when you initialize the middleware: <code>cookie: { maxAge: 3600000 }<\/code> (that\u2019s 1 hour in milliseconds). In Rails, you do <code>expire_after: 1.hour<\/code> in your session store config. My controllers all have that set by default\u2014no exceptions. I\u2019ve seen so many apps where old sessions are cluttering up the server, and it\u2019s just avoidable. Also, never use sessions to store sensitive data like credit card numbers or passwords. Wait, even the session is on your server\u2014if your server gets hacked, that data is gone. So sessions are for non-sensitive, transient data. For sensitive stuff, use encrypted cookies or your DB.<\/p>\n<p>Third mistake: putting session logic in the view or model, not the controller. I get it\u2014views are where you display stuff, so it\u2019s tempting to write things like <code>if session.cart has items, show them<\/code>. But when you put that logic in your controller, it\u2019s testable, reusable, and way easier to debug. Let\u2019s say later you want to add guest checkout\u2014you can reuse the cart session code without touching your view. As a controller vendor, that\u2019s a big selling point: all session-related logic is centralized in the controller, so you don\u2019t have spaghetti code spread across your app.<\/p>\n<p>Wait, let\u2019s switch gears a bit and talk about when to <em>not<\/em> use sessions, just so you know. Sessions are great for small, per-user data, but if you need to share data across <em>all<\/em> users, or store data that needs to persist forever, sessions aren\u2019t for that. That\u2019s what your DB is for. I also don\u2019t use sessions for anonymous users who aren\u2019t doing anything\u2014like someone just browsing the homepage. We only create a session when the user actually takes an action (adds to cart, logs in) to cut down on server load. That\u2019s a choice that a lot of new devs don\u2019t make, and their servers end up with thousands of useless sessions after a few days.<\/p>\n<p>Let\u2019s test another real-world example: a login controller. When a user logs in, you want to keep them signed in across pages, right? So the controller would set the user ID in the session. Here\u2019s a simple Express login action:<\/p>\n<p>app.post(&#8216;\/login&#8217;, (req, res) =&gt; {<br \/>\n\/\/ Check if the username and password are valid<br \/>\nconst user = User.findOne({ username: req.body.username });<br \/>\nif (user &amp;&amp; user.password === req.body.password) {<br \/>\n\/\/ Valid user! Set the session user ID<br \/>\nreq.session.userId = user.id;<br \/>\n\/\/ Redirect to dashboard<br \/>\nres.redirect(&#8216;\/dashboard&#8217;);<br \/>\n} else {<br \/>\nres.redirect(&#8216;\/login?error=invalid&#8217;);<br \/>\n}<br \/>\n});<\/p>\n<p>Then, in your dashboard controller action, you just pull the user ID from the session and get their data:<\/p>\n<p>app.get(&#8216;\/dashboard&#8217;, (req, res) =&gt; {<br \/>\n\/\/ Check if the user is logged in (has a userId in session)<br \/>\nif (!req.session.userId) {<br \/>\nreturn res.redirect(&#8216;\/login&#8217;);<br \/>\n}<br \/>\n\/\/ Get the user from the DB<br \/>\nconst user = User.findById(req.session.userId);<br \/>\n\/\/ Display dashboard with user data<br \/>\nres.render(&#8216;dashboard&#8217;, { user });<br \/>\n});<\/p>\n<p>That\u2019s so clean, right? The login controller sets the session, the dashboard controller checks it, no messy code. And if the user logs out? Just destroy the session:<\/p>\n<p>app.post(&#8216;\/logout&#8217;, (req, res) =&gt; {<br \/>\nreq.session.destroy();<br \/>\nres.redirect(&#8216;\/&#8217;);<br \/>\n});<\/p>\n<p>Done. No more session, user is logged out, perfect.<\/p>\n<p>Now, if you\u2019re using frameworks like Rails, it\u2019s almost identical\u2014just shorter. The Rails controller has a <code>session<\/code> hash built in, so the login action would be something like:<\/p>\n<p>def create<br \/>\nuser = User.find_by(username: params[:username])<br \/>\nif user&amp;.authenticate(params[:password])<br \/>\nsession[:user_id] = user.id<br \/>\nredirect_to dashboard_path<br \/>\nelse<br \/>\nredirect_to login_path, alert: &quot;Invalid login&quot;<br \/>\nend<br \/>\nend<\/p>\n<p>Same logic, just Rails syntax. The key takeaway here is that regardless of the framework, sessions in controllers follow the same pattern: set the session when a user does something, get the session for every subsequent request, destroy it when done.<\/p>\n<p>Wait, let\u2019s talk about a more advanced use case, because sessions can do more than just carts and logins. What if you have a multi-step form, like a checkout process where you fill out shipping info, then payment, then review? You can stash each step\u2019s data in the session so the user doesn\u2019t have to re-fill all fields if they go back a step. Let\u2019s say step 1 is shipping info, step 2 is payment. The shipping controller action would save the shipping data to the session:<\/p>\n<p>class ShippingController &lt; ApplicationController<br \/>\ndef update<br \/>\nsession[:checkout_data] ||= {}<br \/>\nsession[:checkout_data][:shipping] = params[:shipping]<br \/>\nredirect_to payment_path<br \/>\nend<br \/>\nend<\/p>\n<p>Then the payment controller can pull that data, so if the user goes back to edit shipping, it\u2019s already filled in. That\u2019s a lifesaver for users, and it\u2019s all done in the controller\u2014no need to save partial data to the DB until they hit submit. As a controller vendor, I\u2019ve built this exact functionality for clients, and it cuts form abandonment rates by like 20% on average. It\u2019s simple, it\u2019s effective, and it\u2019s all because sessions live right in the controller, where they belong.<\/p>\n<p>Now, let\u2019s cover a few edge cases that come up all the time. What if a user has multiple tabs open? Sessions are per browser, so if they open your site in two tabs, each has its own session. That\u2019s fine, no problem. What if a user clears their cookies? Their session is gone, which is expected\u2014they\u2019ll just have to log in again, or rebuild their cart. If you want \u201cremember me\u201d functionality, you don\u2019t use the session for that\u2014you use a long-lived encrypted cookie with a token, stored in the DB, and tie that to the user. That\u2019s a separate thing, and it\u2019s worth noting because a lot of devs mix session and long-lived auth tokens.<\/p>\n<p>Another edge case: server scaling. If you\u2019re using multiple servers (like load-balancing across 3 instances), you can\u2019t store sessions on a single server\u2019s memory\u2014you need to use a shared session store, like Redis or a database. That\u2019s where my controller work comes in: I build controllers that are compatible with all major session stores, so you can scale without rewriting your session logic. It\u2019s a small detail, but it\u2019s the difference between your app working when you get 10k users and crashing when you get 100k.<\/p>\n<p>Let\u2019s wrap this up with a quick recap, because I know there\u2019s a lot here. Sessions in controllers are perfect for transient, per-user data that needs to stick between requests. The steps are: 1) Set up session middleware in your controller\u2019s framework, 2) Store small, non-sensitive, user-specific data in the session (cart items, user IDs, multi-step form data), 3) Never store sensitive data or large blobs, 4) Set session expiration to clean up old data, 5) Destroy sessions when users log out, and 6) Keep all session logic in the controller, not in views or models.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.busbarwelder.com\/uploads\/44188\/small\/automatic-copper-braided-wire-shunt-cutting44143.png\"><\/p>\n<p>If you\u2019re building an app and you\u2019re tired of dealing with messy session logic that breaks when you scale, or you need a controller that\u2019s optimized for session management and performance, feel free to reach out for a sourcing and pricing chat. We can build controllers tailored to your app\u2019s needs, whether it\u2019s an e-commerce cart, a membership site, or a custom enterprise tool. No generic solutions, no hidden fees\u2014just controllers that work the way you need them to.<\/p>\n<h2>References<\/h2>\n<p><a href=\"https:\/\/www.busbarwelder.com\/welding-accessory\/controller\/\">Controller<\/a> Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming<br \/>\nRails Guides: Action Controller Overview<br \/>\nExpress.js Official Documentation<\/p>\n<hr>\n<p><a href=\"https:\/\/www.busbarwelder.com\/\">Wuxi Haifei Intelligent Equipment Co., Limited<\/a><br \/>Wuxi Haifei Intelligent Equipment Co., Limited is well-known as one of the leading controller manufacturers and suppliers in China. Please rest assured to buy high quality controller made in China here from our factory. For price consultation, contact us.<br \/>Address: 28 Shuiyun Road, Yuecheng, Jiangyin, Jiangsu Province, China. 214400<br \/>E-mail: wd07@busbarwelder.com<br \/>WebSite: <a href=\"https:\/\/www.busbarwelder.com\/\">https:\/\/www.busbarwelder.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey everyone, let\u2019s cut to the chase\u2014if you\u2019re a software dev, building a custom ERP, e-commerce &hellip; <a title=\"How to use session in a controller?\" class=\"hm-read-more\" href=\"http:\/\/www.thietkewebbmt.com\/blog\/2026\/11\/21\/how-to-use-session-in-a-controller-4679-0d31b7\/\"><span class=\"screen-reader-text\">How to use session in a controller?<\/span>Read more<\/a><\/p>\n","protected":false},"author":270,"featured_media":928,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[891],"class_list":["post-928","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-controller-4918-0d6a01"],"_links":{"self":[{"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/posts\/928","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/users\/270"}],"replies":[{"embeddable":true,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/comments?post=928"}],"version-history":[{"count":0,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/posts\/928\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/posts\/928"}],"wp:attachment":[{"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/media?parent=928"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/categories?post=928"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.thietkewebbmt.com\/blog\/wp-json\/wp\/v2\/tags?post=928"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}