Permix

Hydration (SSR)

Learn how to hydrate and dehydrate permissions in your application

Overview

Hydration is the process of converting server-side state into client-side state. In Permix, hydration allows you to serialize permissions on the server and restore them partially on the client.

Note that function-based permissions will be converted to false during dehydration since functions cannot be serialized to JSON. That's why you should call setup method on the client side immediately after hydration.

Usage

Permix provides two methods for handling hydration:

  • dehydrate - Converts the current permissions state into a JSON-serializable format
  • hydrate - Restores permissions from a previously dehydrated state
import { , ,  } from 'permix'
 
const  = <{
  : {
    : { : boolean }
    : 'create' | 'read'
  }
}>()
 
// Set up initial permissions
.({
  : {
    : true,
    :  => .
  }
})
 
// Dehydrate permissions to JSON
const  = ()
// Result: { post: { create: true, read: false } }
 
// Later, hydrate permissions from the state
(, )

Server-Side Rendering

Hydration is particularly useful in server-side rendering scenarios where you want to transfer permissions from the server to the client:

// Express server
import  from 'express'
import { ,  } from 'permix'
 
const  = ()
const  = <{
  : {
    : 'create' | 'read'
  }
}>()
 
.('/', (, ) => {
  // Setup permissions on the server
  .({
    : {
      : true,
      : true
    }
  })
 
  // Dehydrate permissions for client
  const  = ()
 
  // Send HTML with embedded permissions data
  .(`
    <!DOCTYPE html>
    <html>
      <head>
        <script>
          window.__INITIAL_PERMISSIONS__ = ${.()};
        </script>
      </head>
      <body>
        <div id="app"></div>
        <script type="module">
          // Client-side code
          import { createPermix, hydrate } from 'https://cdn.jsdelivr.net/npm/permix/+esm'
 
          const permix = createPermix();
 
          // Hydrate permissions from server data
          hydrate(permix, window.__INITIAL_PERMISSIONS__);
 
          // After hydration, you should call setup again
          // on the client side to fully restore permissions
        </script>
      </body>
    </html>
  `)
})

On this page