Reader small image

You're reading from  Full Stack Web Development with Remix

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781801075299
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Andre Landgraf
Andre Landgraf
author image
Andre Landgraf

Andre is a full stack developer from Germany. He graduated with an MS in Information Systems from the Technical University of Munich and was also awarded an MS in Computer Science from Sofia University in Palo Alto. Andre currently lives in Cupertino, California, and he works as a Software Engineer at LinkedIn. Andre loves learning, writing, and speaking about all things web. In his free time, he tutors aspiring developers and builds for the web.
Read more about Andre Landgraf

Right arrow

Session Management

Session management describes the process of preserving data across different user interactions and request-response roundtrips. Session management is crucial to provide personalized experiences on the web. In this chapter, we will work with Remix’s primitives to manage application state and user session data. This chapter covers the following topics:

  • Working with search parameters
  • Creating user sessions with cookies
  • Authenticating access to user data

First, we will work with Remix's primitives to tie application states to URL search parameters. Then, we will utilize HTTP cookies to persist user session data. Finally, we will use the session cookie to authenticate users in loader and action functions.

After reading this chapter, you will understand how to work with search parameters to control application states in Remix. You will also know how to submit forms programmatically using Remix’s useSubmit hook. You will further...

Technical requirements

You can find the code for this chapter here: https://github.com/PacktPublishing/Full-Stack-Web-Development-with-Remix/blob/main/08-session-management/.

Before starting this chapter, follow the instructions in the README.md file in this chapter’s bee-rich folder on GitHub. This README file guides you through adding a User model to the database schema of the BeeRich application. It further helps you initiate a session.server.ts file with some useful helper functions. Note that following the README guide will temporarily break the create and edit expense and income form actions. We will update the code in this chapter. Until then, use the seed data to populate the database for testing purposes.

Working with search parameters

The URL stores information about the user’s current location. We already utilize dynamic route parameters for expense and invoice identifiers. Similarly, we can use URL search parameters to store additional application states.

A URL is the perfect place to persist state that concerns only one or a few pages. In this section, we will use URL search parameters to create a search filter on the expense overview page in BeeRich.

Did you know that Google uses a search parameter to implement search queries? Open google.com and use the search input field to start a new Google search. After pressing Enter, Google navigates you to the search results page. If you inspect the URL, you will see that Google uses a search parameter called q (short for query probably) to store your search query: https://www.google.com/search?q=Using+search+params+in+Remix.run.

Search parameters are key-value pairs that are added to the URL after the pathname following...

Creating user sessions with cookies

A session maintains the state of a user’s interactions with a web application across multiple requests. Sessions track information such as user authentication credentials, shopping cart contents, color scheme preferences, and other user-specific data. In this section, we will use Remix’s session cookie helpers to create a login and signup flow in BeeRich.

One way to manage sessions is via cookies. Cookies contain small pieces of data and are appended to both document and fetch requests, making them a great way to handle user sessions, personalization, and tracking. Additionally, cookies can be encrypted to securely carry user credentials without client access.

Cookies are part of the HTTP protocol and enable persisting information in the otherwise stateless HTTP protocol. Where URL search parameters are visible to the user and can be bookmarked and shared, cookie data can be encrypted and are then only accessible on the server...

Authenticating access to user data

We can access cookies in our loader and action functions as cookies are appended to every HTTP request to the web server. This makes cookies a great tool for managing sessions. In this section, we will read from the session cookie to authenticate users and query user-specific data.

Accessing cookie data on the server

Once we append a cookie to a response, we can access the cookie data on every following request to the server. This lets us build personalized and session-based user experiences. Let’s add some helper functions to make this task easier:

  1. Add the following code to the session.server.ts file:
    export async function getUserId(request: Request) {  const session = await getUserSession(request);  const userId = session.get('userId');  if (!userId || typeof userId !== 'string') return null;  return userId;}export async function getUser(request: Request) {  ...

Summary

In this chapter, you learned about session and state management in Remix. First, you learned how to use URL search parameters to persist application state using Remix’s Form component and the useSearchParams hook. The URL is often all we need to handle application state.

You also practiced using useSubmit to submit a form programmatically and learned more about Remix’s different mutation utilities. We concluded that we use the Form component and the useSubmit hook for the primary actions on the page; useFetcher is used to support concurrent submissions with isolated submission states.

Next, you learned that cookies are part of the HTTP protocol and can be used to persist state across page transitions. Cookies are a great tool for session management. Remix provides helper functions for working with cookies and sessions. Remix’s session primitives allow us to manage sessions using different strategies, such as storing session data in memory, files,...

Further reading

Review the MDN Web Docs for more information about URL search parameters and the URLSearchParams interface: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams.

Also refer to the MDN Web Docs if you want to learn more about HTTP cookies: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies or the Headers interface: https://developer.mozilla.org/en-US/docs/Web/API/Headers.

Refresh your knowledge about HTML forms by reading through the MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form.

Remix provides several primitives for working with sessions. You can find more information in the Remix documentation: https://remix.run/docs/en/2/utils/sessions.

Remix also provides lower-level primitives for working with cookies: https://remix.run/docs/en/2/utils/cookies.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Web Development with Remix
Published in: Nov 2023Publisher: PacktISBN-13: 9781801075299
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Andre Landgraf

Andre is a full stack developer from Germany. He graduated with an MS in Information Systems from the Technical University of Munich and was also awarded an MS in Computer Science from Sofia University in Palo Alto. Andre currently lives in Cupertino, California, and he works as a Software Engineer at LinkedIn. Andre loves learning, writing, and speaking about all things web. In his free time, he tutors aspiring developers and builds for the web.
Read more about Andre Landgraf