ES Modules Logo ESModules.com

Security Best Practices

Protect your applications from security vulnerabilities.

Subresource Integrity (SRI)

Verify that CDN-loaded modules haven't been tampered with:

<script type="module"
  src="https://cdn.example.com/module.js"
  integrity="sha384-abc123..."
  crossorigin="anonymous">
</script>

✅ Benefits: Protects against CDN compromises and man-in-the-middle attacks

Dependency Auditing

Regularly scan dependencies for vulnerabilities:

# npm audit
npm audit
npm audit fix

# Check specific packages
npm audit --json | grep severity

Automated Tools:

  • Dependabot (GitHub)
  • Snyk
  • npm audit
  • Socket Security

Dynamic Import Safety

Be cautious with dynamic imports using user input:

❌ Dangerous:

// User can inject malicious paths
const module = await import(userInput);

✅ Safe:

// Whitelist allowed modules
const allowed = ['en', 'es', 'fr'];
if (allowed.includes(lang)) {
  await import(`./i18n/${lang}.js`);
}

Content Security Policy (CSP)

Restrict module sources with CSP headers:

Content-Security-Policy:
  script-src 'self' https://trusted-cdn.com;
  script-src-elem 'self' https://trusted-cdn.com;

⚠️ Note:

ES Modules respect CSP's script-src directive. Test thoroughly!

Security Checklist

Use SRI for CDN modules
Run npm audit regularly
Validate user input in dynamic imports
Implement CSP headers
Keep dependencies updated
Use HTTPS for all module loads

Lockfiles & Supply Chain

Always commit and use lockfiles:

  • package-lock.json (npm) - ensures exact dependency versions
  • yarn.lock (Yarn) - locks dependency tree
  • pnpm-lock.yaml (pnpm) - reproducible installs
  • Review dependency changes in PRs
  • Use tools like Socket.dev to detect malicious packages

Continue Learning