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:
- 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) { ...