Fix Error: EACCES: permission denied, open '/var/log/app/server.log' in Node.js
This error means Node.js does not have file system permissions to read, write, or execute at the specified path. Common causes include running as the wrong user, incorrect file ownership, or restrictive directory permissions. Fix it by adjusting file permissions, running as the correct user, or writing to a permitted directory.
Reading the Stack Trace
Here's what each line means:
- at Object.openSync (node:fs:603:3): The operating system denied Node's attempt to open the file because the process user lacks the necessary permissions.
- at Logger.write (src/utils/logger.js:18:8): Your logger at line 18 tries to write to a log file in a directory the Node process user cannot access.
- at Object.<anonymous> (src/index.js:6:8): The logger is invoked at startup on line 6, so the permission error crashes the app immediately.
Common Causes
1. Running as non-root user without file permissions
The Node.js process runs as a non-root user that does not have write access to the target directory.
const fs = require('fs');
fs.appendFileSync('/var/log/app/server.log', logEntry);
// Process runs as 'node' user, /var/log/app is owned by root
2. Docker container user cannot access mounted volume
The container runs as a non-root user but the mounted volume has root-only permissions on the host.
# Dockerfile
USER node
# docker run -v /host/logs:/var/log/app myapp
# /host/logs is owned by root, 'node' user can't write
3. Restrictive umask or SELinux policy
A restrictive umask or security policy prevents the process from creating files in the target directory.
// umask 0077 means only the owner can read/write newly created files
fs.writeFileSync('/shared/output.txt', data); // Fails for other users
The Fix
Use an environment variable for the log directory so it can be configured to a writable location in each environment. Create the directory if it does not exist. Catch EACCES specifically to provide a helpful error message.
const fs = require('fs');
class Logger {
write(message) {
fs.appendFileSync('/var/log/app/server.log', message + '\n');
}
}
const fs = require('fs');
const path = require('path');
const LOG_DIR = process.env.LOG_DIR || path.join(process.cwd(), 'logs');
class Logger {
constructor() {
if (!fs.existsSync(LOG_DIR)) {
fs.mkdirSync(LOG_DIR, { recursive: true });
}
this.logPath = path.join(LOG_DIR, 'server.log');
}
write(message) {
try {
fs.appendFileSync(this.logPath, message + '\n');
} catch (err) {
if (err.code === 'EACCES') {
console.error(`Permission denied writing to ${this.logPath}. Set LOG_DIR to a writable directory.`);
}
throw err;
}
}
}
Testing the Fix
const fs = require('fs');
const path = require('path');
const os = require('os');
describe('Logger', () => {
let Logger, tempDir;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'logger-test-'));
process.env.LOG_DIR = tempDir;
jest.resetModules();
Logger = require('./logger').Logger;
});
afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('writes log messages to the configured directory', () => {
const logger = new Logger();
logger.write('test message');
const content = fs.readFileSync(path.join(tempDir, 'server.log'), 'utf8');
expect(content).toContain('test message');
});
it('creates the log directory if it does not exist', () => {
process.env.LOG_DIR = path.join(tempDir, 'subdir', 'logs');
jest.resetModules();
Logger = require('./logger').Logger;
const logger = new Logger();
expect(fs.existsSync(process.env.LOG_DIR)).toBe(true);
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/nodejs-permission-denied-logger,git add src/utils/logger.js src/utils/__tests__/logger.test.js,git commit -m "fix: use configurable log directory and handle EACCES",git push origin fix/nodejs-permission-denied-logger
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run lint
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
const { initBugStack } = require('bugstack-sdk')
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Identify which user the Node.js process runs as.
- Set correct ownership and permissions on the target directory.
- Use an environment variable for the log directory path.
- Run tests to verify write access.
- Open a PR, merge after CI, and verify in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Never run Node.js as root in production. Instead, create a dedicated user, set proper file permissions, and use environment variables to point to writable directories.
In your Dockerfile, create the directory and chown it to the node user before switching to USER node. For mounted volumes, ensure the host directory has matching UID/GID permissions.