Cipherion
Sdk IntegrationsJavaScript SDKFrameworks

Express Integration

Integrate Cipherion with Express.js applications

Express.js Integration

Learn how to integrate Cipherion encryption into your Express.js applications.

Installation

npm install express @cipherion/client dotenv
npm install -D @types/express @types/node typescript ts-node

Basic Setup

1. Initialize Client

src/config/cipherion.ts
import { CipherionClient } from '@cipherion/client';
import * as dotenv from 'dotenv';

dotenv.config();

export const cipherionClient = new CipherionClient({
  baseUrl: process.env.CIPHERION_BASE_URL,
  projectId: process.env.CIPHERION_PROJECT_ID,
  apiKey: process.env.CIPHERION_API_KEY,
  passphrase: process.env.CIPHERION_PASSPHRASE,
  logLevel: 'info'
});

2. Create Middleware

src/middleware/cipherion.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { cipherionClient } from '../config/cipherion';

declare global {
  namespace Express {
    interface Request {
      cipherion: typeof cipherionClient;
    }
  }
}

export const cipherionMiddleware = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  req.cipherion = cipherionClient;
  next();
};

3. Set Up Express App

src/app.ts
import express from 'express';
import { cipherionMiddleware } from './middleware/cipherion.middleware';
import userRoutes from './routes/user.routes';

const app = express();

app.use(express.json());
app.use(cipherionMiddleware);

app.use('/api/users', userRoutes);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

export default app;

User Management Example

Routes

src/routes/user.routes.ts
import { Router } from 'express';
import {
  createUser,
  getUser,
  updateUser,
  listUsers
} from '../controllers/user.controller';

const router = Router();

router.post('/', createUser);
router.get('/:id', getUser);
router.put('/:id', updateUser);
router.get('/', listUsers);

export default router;

Controller

src/controllers/user.controller.ts
import { Request, Response } from 'express';
import { CipherionError } from '@cipherion/client';
import User from '../models/user.model';

export const createUser = async (req: Request, res: Response) => {
  try {
    const userData = req.body;
    
    // Encrypt sensitive fields
    const encrypted = await req.cipherion.deepEncrypt(userData, {
      exclude_fields: ['username', 'role'],
      exclude_patterns: ['*_at', '_id']
    });
    
    // Save to database
    const user = new User({
      ...encrypted.encrypted,
      _encrypted: true,
      _encryptionMeta: encrypted.meta
    });
    
    await user.save();
    
    res.status(201).json({
      success: true,
      userId: user._id,
      billableFields: encrypted.meta.billableFields
    });
  } catch (error) {
    if (error instanceof CipherionError) {
      res.status(error.statusCode).json({
        success: false,
        message: error.getUserMessage()
      });
    } else {
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    }
  }
};

export const getUser = async (req: Request, res: Response) => {
  try {
    const user = await User.findById(req.params.id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: 'User not found'
      });
    }
    
    // Decrypt data
    const decrypted = await req.cipherion.deepDecrypt(user.toObject(), {
      exclude_fields: ['username', 'role'],
      exclude_patterns: ['*_at', '_id'],
      fail_gracefully: true
    });
    
    // Remove internal fields
    const { _encrypted, _encryptionMeta, ...userData } = decrypted.data;
    
    res.json({
      success: true,
      data: userData
    });
  } catch (error) {
    if (error instanceof CipherionError) {
      res.status(error.statusCode).json({
        success: false,
        message: error.getUserMessage()
      });
    } else {
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    }
  }
};

export const updateUser = async (req: Request, res: Response) => {
  try {
    const updates = req.body;
    
    // Encrypt updates
    const encrypted = await req.cipherion.deepEncrypt(updates, {
      exclude_fields: ['username', 'role'],
      exclude_patterns: ['*_at']
    });
    
    const user = await User.findByIdAndUpdate(
      req.params.id,
      { 
        ...encrypted.encrypted,
        updatedAt: new Date()
      },
      { new: true }
    );
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: 'User not found'
      });
    }
    
    res.json({
      success: true,
      message: 'User updated successfully'
    });
  } catch (error) {
    if (error instanceof CipherionError) {
      res.status(error.statusCode).json({
        success: false,
        message: error.getUserMessage()
      });
    } else {
      res.status(500).json({
        success: false,
        message: 'Internal server error'
      });
    }
  }
};

export const listUsers = async (req: Request, res: Response) => {
  try {
    const users = await User.find().select('-_encrypted -_encryptionMeta');
    
    // Decrypt all users
    const decrypted = await Promise.all(
      users.map(user => 
        req.cipherion.deepDecrypt(user.toObject(), {
          exclude_fields: ['username', 'role'],
          exclude_patterns: ['*_at', '_id'],
          fail_gracefully: true
        })
      )
    );
    
    res.json({
      success: true,
      count: users.length,
      data: decrypted.map(d => d.data)
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Internal server error'
    });
  }
};

Error Handling Middleware

src/middleware/error.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { CipherionError } from '@cipherion/client';

export const errorHandler = (
  error: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (error instanceof CipherionError) {
    return res.status(error.statusCode).json({
      success: false,
      message: error.getUserMessage(),
      ...(process.env.NODE_ENV === 'development' && {
        details: error.details,
        stack: error.stack
      })
    });
  }
  
  console.error('Unexpected error:', error);
  
  res.status(500).json({
    success: false,
    message: 'Internal server error'
  });
};

// Add to app.ts
app.use(errorHandler);

Service Layer Pattern

src/services/encryption.service.ts
import { cipherionClient } from '../config/cipherion';
import { CipherionError } from '@cipherion/client';

export class EncryptionService {
  private readonly excludeOptions = {
    exclude_fields: ['_id', 'username', 'role'],
    exclude_patterns: ['*_at', '*_id']
  };
  
  async encryptUserData(data: any) {
    try {
      return await cipherionClient.deepEncrypt(data, this.excludeOptions);
    } catch (error) {
      if (error instanceof CipherionError && error.isRetryable()) {
        // Retry once after delay
        await this.delay(2000);
        return await cipherionClient.deepEncrypt(data, this.excludeOptions);
      }
      throw error;
    }
  }
  
  async decryptUserData(data: any) {
    return await cipherionClient.deepDecrypt(data, {
      ...this.excludeOptions,
      fail_gracefully: true
    });
  }
  
  private delay(ms: number) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

export const encryptionService = new EncryptionService();

Rate Limiting

src/middleware/rate-limit.middleware.ts
import rateLimit from 'express-rate-limit';

export const encryptionRateLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // Limit each IP to 100 requests per windowMs
  message: 'Too many encryption requests, please try again later',
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply to encryption routes
app.use('/api/users', encryptionRateLimiter);

Complete Project Structure

express-cipherion-app/
├── src/
│   ├── config/
│   │   └── cipherion.ts
│   ├── controllers/
│   │   └── user.controller.ts
│   ├── middleware/
│   │   ├── cipherion.middleware.ts
│   │   ├── error.middleware.ts
│   │   └── rate-limit.middleware.ts
│   ├── models/
│   │   └── user.model.ts
│   ├── routes/
│   │   └── user.routes.ts
│   ├── services/
│   │   └── encryption.service.ts
│   └── app.ts
├── .env
├── package.json
└── tsconfig.json