Getting started with Remix: A thorough explanation of session management - How to register and log in

I will show you how to use Remix to manage sessions. cookie as the session storage to manage sessions.

In this article, session management is defined as "maintaining the logged-in state from the time a user logs in to the time they log out."

How to manage sessions

Remix cookie To manage sessions using , you need to do three things:

1. Create session storage

createCookieSessionStorage to prepare for using cookies as session storage.

Example: app/sessions.js

import { createCookieSessionStorage } from "@remix-run/node" ;

 const { getSession, commitSession, destroySession } = createCookieSessionStorage(
 {
 cookie: {
 name: "__session" ,
 // 自身のサイトのドメインとする
 domain: process.env.DOMAIN,
 httpOnly: true ,
 maxAge: 3600 ,
 path: "/" ,
 sameSite: "lax" ,
 secrets: [ "s3cret1" ],
 // localhostの場合はhttpsではないので、プロダクションのみtrueとする 
secure: process.env.NODE_ENV === "production" ? true : false
 },
 }
 );

 export { getSession, commitSession, destroySession };

    2. When login is successful, store the userID in the session storage and set a cookie.

    getSession to get the current session and store the user's ID against it to determine "who is the logged in user".

    Also, commitSession and Set-Cookie to confirm the storage of the user ID. cookie Set it to.

    Example: app/routes/login.jsx

    import { getSession, commitSession } from "~/sessions" ;
    
     // ...
    
     export const action = async ({ request }) => {
     const session = await getSession(request.headers.get( "Cookie" ));
    
     // ... 認証処理
    const userId = "取得したユーザーのID"
    
     // セッションストレージにuserIdを格納
     session.set( "userId" , String (userId));
    
     // Set-Cookie を使って、cookieをセット 
    const headers = { "Set-Cookie" : await commitSession(session) }
     return redirect( "/" , { headers })
     }
    
     // ...
    

    cookie To userId As long as this is maintained, the user is considered to be logged in.

    In addition, the stored userId teeth getSession For the session obtained by session.get("userId") It is possible to obtain it by

    Example: app/routes/users.jsx

     import { getSession, commitSession } from "~/sessions" ;
    
     // ...
     
    export const loader = async ({ request }) => {
     const session = await getSession(request.headers.get( "Cookie" ));
     // Check if logged in
     if (!session.has( "userId" )) {
     return redirect( "/login" )
     }
    
     // Get userId
     const userId = session.get( "userId" )
    
     // ...
     }
    
     // ...

    3. Discard the session when logging out.

    Just like when you stored the user ID, destroySession and Set-Cookie Use to discard the session and cookie Make the changes.

    Example: app/routes/users.jsx

     import { getSession, commitSession, destroySession } from "~/sessions" ;
    
     // ...
    
     export const action = async ({ request }) => {
     const session = await getSession(request.headers.get( "Cookie" ));
    
     // セッションを破棄 
    return redirect( "/" , { headers: { "Set-Cookie" : await destroySession(session) }} )
     }
    
     // ...
    

    Important points to note

    One cookie can only hold a maximum of 4KB of information.

    cookie As a session storage method, userID or (if used) Flashメッセージ On the client side cookie Since the data will be stored in the memory, you need to be careful about the maximum capacity.

    If you want to retain more information, RDBMS Prepare a separate database and use it as session storage.

    Back to blog

    Leave a comment

    Please note, comments need to be approved before they are published.