A module to make using Cloudflare Pages environment variables and KV-backed sessions easier with Remix.
The remix-pages-context package is designed to simplify the usage of Cloudflare Pages’ environment variables and KV-backed sessions. It provides a convenient way to set up server configuration and access typed environment variables and session values.
getLoadContext and getPagesContext, to access your typed environment variables and session values anywhere within your codebase.To install and use the remix-pages-context package, follow these steps:
Step 1: Set up server.ts:
// Import required modules and packages
import { createRequestHandler } from "@remix-run/express";
import { createSessionsLoader } from "@remix-run/cookie-session";
import { createRequestValidator } from "@remix-run/validator";
import { yourSchemas } from "./schemas"; // Import your Zod schemas
// Create a typed context object
const context = {
// Define your environment variables and session values schemas using Zod
env: yourSchemas.envSchema,
session: yourSchemas.sessionSchema,
// Other properties...
};
// Set up the request handler
export default createRequestHandler({
getLoadContext() {
// Return the typed context object
return context;
},
session: createSessionsLoader(), // Optional session loader
// Other options...
});
Step 2: Destructure getLoadContext and getPagesContext off the context object:
import { getLoadContext, getPagesContext } from "remix-pages-context";
// Use getLoadContext to create the Pages function handler
const pagesHandler = getLoadContext().createPagesFunctionHandler();
// Use getPagesContext to access typed environment variables and session values
const { env, session } = getPagesContext();
Step 3: Use getPagesContext anywhere you want to access your typed environment variables and session values:
// Example usage
console.log(env.MY_ENV_VARIABLE);
console.log(session.MY_SESSION_VALUE);
The remix-pages-context package provides a convenient and efficient way to work with Cloudflare Pages’ environment variables and KV-backed sessions. By utilizing typed contexts and helper functions, developers can easily access and manage their environment variables and session values with confidence.