Production Engineering/
Lesson

Privacy regulations can feel like bureaucratic noise until you receive a regulator's letter or a lawyer's email. GDPRWhat is gdpr?A European regulation that gives users control over their personal data, including the right to access, delete, and export it. fines run up to 4% of global annual revenue, for a startup that means existential risk. But beyond the legal risk, handling user data responsibly is just the right thing to do. This lesson gives you a practical understanding of what compliance actually requires in code and process.

Understanding personal data

The first step to compliance is understanding what counts as personal data. It's much broader than just names and email addresses.

Under GDPRWhat is gdpr?A European regulation that gives users control over their personal data, including the right to access, delete, and export it., personal data is any information that can identify a person, directly or indirectly. That includes:

Data typeExamples
Direct identifiersName, email, phone number, national ID
Indirect identifiersIP address, cookie ID, device fingerprint
Sensitive data (special category)Health data, biometrics, religion, political opinion
Behavioral dataBrowsing history, purchase history, location data
Sensitive data (called "special category" data in GDPR) has stricter rules. You generally need explicit consent to process it, and you should avoid collecting it unless absolutely necessary. If you're building a health app, read the regulation carefully before you touch any medical information.

If your application logs request IP addresses, which almost all applications do, you're processing personal data. That means GDPR applies to you if any of your users are in the EU, regardless of where your company is based.

02

Core GDPRWhat is gdpr?A European regulation that gives users control over their personal data, including the right to access, delete, and export it. principles

GDPR is built on a set of principles. You don't need to memorize the regulation, but you do need to understand these:

Lawful basis for processing

You must have a legal reason to process personal data. The most common ones for web applications are:

  • Consent: the user explicitly agreed (opt-in, not opt-out, not pre-ticked boxes)
  • Contract: processing is necessary to fulfill a contract with the user (e.g., an email address to send a receipt)
  • Legitimate interest: your interest in processing data outweighs the user's privacy interest (requires a documented assessment)
// Record consent with a timestamp and the exact version of your privacy policy
interface ConsentRecord {
  userId: string;
  type: 'marketing' | 'analytics' | 'functional';
  granted: boolean;
  timestamp: string;         // ISO 8601
  privacyPolicyVersion: string;
  ipAddress: string;         // evidence of consent
}

async function recordConsent(
  userId: string,
  type: ConsentRecord['type'],
  granted: boolean
): Promise<void> {
  await db.prepare(`
    INSERT INTO consent_records
    (user_id, type, granted, timestamp, policy_version, ip_address)
    VALUES (?, ?, ?, ?, ?, ?)
  `).bind(
    userId, type, granted,
    new Date().toISOString(),
    CURRENT_POLICY_VERSION,
    requestIp
  ).run();
}

Data minimization

Only collect data you actually need for a specific, documented purpose. If you don't have a clear reason to collect a field, don't collect it. This principle keeps your compliance burden smaller and reduces the impact of a potential breach.

// BAD: collecting more than you need
interface UserRegistration {
  email: string;
  password: string;
  fullName: string;
  phoneNumber: string;       // do you actually need this?
  dateOfBirth: string;       // only if legally required (e.g., age verification)
  address: string;           // only if you're shipping physical goods
  marketingOptIn: boolean;
}

// BETTER: minimal registration
interface UserRegistration {
  email: string;
  password: string;
  displayName: string;       // user-chosen, not necessarily real name
}
03

User rights you must support

GDPRWhat is gdpr?A European regulation that gives users control over their personal data, including the right to access, delete, and export it. gives users specific rights that you must be able to fulfill.

RightWhat it meansImplementation
Right of accessUser can request all data you hold on them"Download my data" feature
Right to erasureUser can request deletion of their dataDelete account + cascade
Right to portabilityUser can request data in a machine-readable formatExport as JSON or CSV
Right to rectificationUser can correct inaccurate dataProfile edit functionality
Right to objectUser can opt out of certain processing (e.g., marketing)Unsubscribe, preference center
// Implementing "download my data" (right of access)
app.get('/api/user/export', requireAuth, async (req, res) => {
  const userId = req.user.id;

  const [user, orders, activityLog] = await Promise.all([
    db.prepare('SELECT id, email, display_name, created_at FROM users WHERE id = ?')
      .bind(userId).first(),
    db.prepare('SELECT * FROM orders WHERE user_id = ?')
      .bind(userId).all(),
    db.prepare('SELECT * FROM activity_log WHERE user_id = ? ORDER BY timestamp DESC')
      .bind(userId).all(),
  ]);

  res.setHeader('Content-Disposition', 'attachment; filename="my-data.json"');
  res.json({
    exportedAt: new Date().toISOString(),
    profile: user,
    orders: orders.results,
    activityLog: activityLog.results,
  });
});

// Implementing "delete my account" (right to erasure)
app.delete('/api/user', requireAuth, async (req, res) => {
  const userId = req.user.id;

  // Use a transaction to ensure all data is deleted atomically
  await db.batch([
    db.prepare('DELETE FROM sessions WHERE user_id = ?').bind(userId),
    db.prepare('DELETE FROM activity_log WHERE user_id = ?').bind(userId),
    db.prepare('DELETE FROM orders WHERE user_id = ?').bind(userId),
    db.prepare('DELETE FROM users WHERE id = ?').bind(userId),
  ]);

  res.json({ message: 'Account deleted.' });
});
The right to erasure is not absolute. You may be required to retain certain data for legal reasons (tax records, fraud investigations). In those cases, you can "pseudonymize" the user, replace identifying information with an anonymous ID, rather than deleting the underlying transaction records.
04

Data breach response

If personal data is compromised, GDPRWhat is gdpr?A European regulation that gives users control over their personal data, including the right to access, delete, and export it. requires you to notify the relevant supervisory authority within 72 hours of becoming aware of the breach (if it's likely to result in a risk to individuals). This means you need a process before a breach happens, not after.

What to document and report

markdown
# Data breach report template

## Nature of the breach
- Type: unauthorized access / accidental exposure / ransomware
- Data involved: [list the categories and approximate number of records]
- Systems affected: [which databases, services, files]

## Timeline
- When it occurred: [date/time]
- When discovered: [date/time]
- When contained: [date/time]

## Likely impact on individuals
- Risk level: low / medium / high
- Nature of risk: identity theft / financial harm / reputational damage

## Measures taken
- Immediate containment steps
- Long-term remediation

## Regulator notification required?
- High/medium risk → notify supervisory authority within 72 hours
- Very high risk → also notify affected individuals directly
05

Practical compliance checklist

You don't need to become a lawyer to build a compliant application. Start with these concrete steps:

StepDescriptionPriority
Privacy policyDocument what data you collect, why, how long you keep itRequired before launch
Cookie consentImplement a consent banner for non-essential cookiesRequired for EU users
Data deletionBuild "delete my account" that removes all personal dataRequired
Data exportBuild "download my data" in JSON or CSV formatRequired
Breach response planDocument who to notify and how, before you need itRequired
Data retention limitsDefine and enforce how long you keep each data typeGood practice
Vendor reviewEnsure third-party services (analytics, CDN) are GDPR-compliantGood practice
GDPR compliance is not just a backend concern. Your analytics setup, A/B testing tools, advertising pixels, and even your font CDN (if it loads from Google Fonts) all involve data transfers that may require consent or a data processing agreement with the vendor.