Persisting Data and Secrets Across Glitch Container Restarts
Glitch restarts your Node.js container on code changes and idle sleep. Keep runtime files in .data, secrets in .env, and design for cold starts.
28 Nov 2025, 18:34 UTC

The Problem: Ephemeral Containers, Persistent Expectations
Glitch runs your Node.js project inside a container that restarts whenever you edit files, stop and start the project, or when the platform recycles it. Every restart wipes the filesystem except for one directory: .data. If your application writes uploads, SQLite files, or logs anywhere else, that data disappears on the next restart. Free projects also sleep after a period without inbound requests, so clients must tolerate a cold-start delay rather than assuming a warm server.
Desired Outcome
A Glitch project that survives restarts without losing runtime state, keeps credentials out of source code, and wakes from sleep without breaking dependent clients or scheduled jobs.
Prerequisites
- An existing Node.js project on Glitch (or a remix you control).
- Edit access to the project, because
.envis readable by anyone with edit permissions. - Node.js and
npmfundamentals; Glitch starts the app withnpm startdefined inpackage.json.
Focused Procedure
1. Write Only Inside .data
Resolve the persistent path relative to the project root. Glitch commonly runs the app from /app, but hard-coding that path is fragile. Use path.join(process.cwd(), '.data') so the code works regardless of the absolute mount point.
Create the directory before the first write so a fresh container does not crash on an empty volume:
const fs = require('fs');
const path = require('path');
const dataDir = path.join(process.cwd(), '.data');
// Ensure the directory exists before any read/write
fs.mkdirSync(dataDir, { recursive: true });
// Example: append a timestamped log entry
const logLine = `${new Date().toISOString()} request received\n`;
fs.appendFileSync(path.join(dataDir, 'access.log'), logLine);
Where to run: This code runs inside your Glitch application process. No special permissions are required beyond the Node.js process itself.
Expected check: After deploying, open the Glitch terminal and run ls -la .data. You should see the files your app created.
Risk: Writing outside .data (for example, to /tmp or the project root) is lost on restart, including mid-request if a file change triggers a restart.
2. Keep Secrets in .env
Create a .env file at the project root and reference values through process.env. Glitch injects these variables into the application environment at start time.
# .env (project root)
DATABASE_URL=postgres://user:[contact removed]:5432/dbname
API_KEY=replace-with-your-secret
// Read in application code
const apiKey = process.env.API_KEY;
if (!apiKey) {
throw new Error('API_KEY is not set in .env');
}
Where to run: Create and edit .env in the Glitch editor. Do not commit it to a public Git remote if you also mirror the project elsewhere.
Expected check: Temporarily add console.log(Object.keys(process.env).filter(k => k === 'API_KEY')) to confirm injection, then remove the line.
Risk: .env is hidden from people who view a public project, but anyone with edit access can read it. Rotate secrets before sharing a project or adding collaborators.
3. Make Writes Restart-Safe
Glitch restarts the container when watched files change. watch.json controls which paths trigger a restart. If a restart lands in the middle of a file write, the file can be truncated or corrupted.
Keep long-running work out of request handlers. For critical writes, use atomic patterns: write to a temporary file inside .data, then rename it over the target.
const fs = require('fs');
const path = require('path');
const dataDir = path.join(process.cwd(), '.data');
const target = path.join(dataDir, 'state.json');
const tmp = path.join(dataDir, 'state.json.tmp');
fs.writeFileSync(tmp, JSON.stringify({ updated: Date.now() }));
fs.renameSync(tmp, target); // Atomic on the same volume
Expected check: Edit an unrelated watched file while the endpoint is under load. The state.json file should contain either the old or new content, never a partial write.
4. Tolerate Idle Sleep on Free Projects
Free (non-boosted) Glitch projects sleep after a period without inbound requests. The next request wakes the container, adding cold-start latency. Health checks, cron jobs, and browser clients must retry or extend timeouts rather than treating the first slow response as a failure.
If you use an external uptime monitor, set its timeout above the observed cold-start delay. If a scheduled job calls your app, wrap the call in a retry with backoff.
Expected Checks
| Check | How to verify |
|---|---|
| Persistence across restart | Call an endpoint that writes to .data, stop the project, start it again, and confirm the file still exists. |
| Secret injection | Log only the key names from process.env (never the values) and confirm API_KEY appears. |
| Cold-start latency | Leave the project idle, then time the first request. Compare against a boosted project if you have one. |
| Restart-safe writes | Trigger a file change during a write and confirm the target file is never partially written. |
Recovery Options and Limitations
Glitch's Rewind feature restores project files, but do not assume it restores .data. Remixing a project copies the code but starts with an empty .data directory. A single per-project .data volume is a single point of failure.
For critical data, back up to an external store on a schedule. A simple approach is to periodically copy .data contents to an object storage bucket or a managed database. If you lose .data and have no external backup, recovery is limited.
Platform Volatility
Glitch's sleep timers, free-tier limits, and persistence guarantees are platform-managed and change over time. Verify current behavior in Glitch's help documentation before relying on any specific timeout or restore capability. The patterns above—isolating persistent state in .data, injecting secrets through .env, and designing for cold starts—remain sound engineering practices regardless of exact platform thresholds.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.