0
# Session Storage
1
2
File-based session storage that persists session data to the filesystem with automatic expiration handling and secure session ID generation.
3
4
## Capabilities
5
6
### Create File Session Storage
7
8
Creates a SessionStorage that stores session data on a filesystem with automatic cleanup of expired sessions.
9
10
```typescript { .api }
11
/**
12
* Creates a SessionStorage that stores session data on a filesystem
13
* @param options - Configuration options for file session storage
14
* @returns SessionStorage instance for managing sessions
15
*/
16
function createFileSessionStorage<Data = SessionData, FlashData = Data>(
17
options: FileSessionStorageOptions
18
): SessionStorage<Data, FlashData>;
19
20
interface FileSessionStorageOptions {
21
/** The Cookie used to store the session id on the client, or options used to automatically create one */
22
cookie?: SessionIdStorageStrategy["cookie"];
23
/** The directory to use to store session files */
24
dir: string;
25
}
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
import { createFileSessionStorage } from "@remix-run/node";
32
33
// Basic file session storage
34
const sessionStorage = createFileSessionStorage({
35
dir: "/tmp/sessions"
36
});
37
38
// With custom cookie configuration
39
const sessionStorage = createFileSessionStorage({
40
dir: "./app/sessions",
41
cookie: {
42
name: "__session",
43
maxAge: 86400, // 24 hours
44
httpOnly: true,
45
secure: process.env.NODE_ENV === "production",
46
sameSite: "lax",
47
secrets: ["session-secret-key"]
48
}
49
});
50
51
// Use in a Remix loader
52
export async function loader({ request }: LoaderFunctionArgs) {
53
const session = await sessionStorage.getSession(
54
request.headers.get("Cookie")
55
);
56
57
const userId = session.get("userId");
58
59
return json({ userId });
60
}
61
62
// Use in a Remix action
63
export async function action({ request }: ActionFunctionArgs) {
64
const session = await sessionStorage.getSession(
65
request.headers.get("Cookie")
66
);
67
68
session.set("userId", "user123");
69
70
return redirect("/dashboard", {
71
headers: {
72
"Set-Cookie": await sessionStorage.commitSession(session)
73
}
74
});
75
}
76
```
77
78
**File Organization:**
79
80
Session files are organized using a two-level directory structure to optimize filesystem performance:
81
82
- Session ID is split into directory (first 4 characters) and filename (remaining characters)
83
- Maximum of 2^16 directories, each with up to 2^48 files
84
- Example: Session ID `abcd1234567890ef` becomes `/sessions/abcd/1234567890ef`
85
86
**Security Features:**
87
88
- **Cryptographically secure session IDs**: Uses Node.js Web Crypto API for random session ID generation
89
- **Automatic collision avoidance**: Regenerates IDs if file already exists
90
- **Automatic cleanup**: Expired sessions are automatically removed when accessed
91
- **Large ID space**: 2^64 possible session IDs prevent brute force attacks
92
93
**Storage Operations:**
94
95
The file session storage handles all standard session operations:
96
97
- **Create**: Generates unique session ID and stores data as JSON
98
- **Read**: Retrieves session data and checks expiration
99
- **Update**: Updates existing session data with new expiration
100
- **Delete**: Removes session file from filesystem
101
- **Commit**: Serializes session changes to cookie
102
- **Destroy**: Removes session and clears cookie
103
104
**Error Handling:**
105
106
- **ENOENT errors**: Gracefully handled for missing session files
107
- **EEXIST errors**: Handled during session ID collision resolution
108
- **Permission errors**: Automatically creates directory structure
109
- **Expired sessions**: Automatically cleaned up on access
110
111
**Performance Considerations:**
112
113
- **Lazy evaluation**: Sessions are only read when accessed
114
- **Atomic writes**: Uses `wx` flag to prevent race conditions
115
- **Directory structure**: Optimized for filesystems with large file counts
116
- **JSON serialization**: Simple and efficient session data storage