Examples & Use Cases

Real-world examples and practical solutions using the images-watermark npm package. From basic text watermarks to advanced batch processing, learn how to protect and brand your images effectively.

Quick Start Examples

Basic Text Watermark

Add a simple copyright text watermark to protect your images

Beginner
Perfect for photographers and content creators
basic-text-watermark.js
1const { singleImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function addBasicTextWatermark(req, res) {
5  try {
6    const watermarkedImage = await singleImageWatermark({
7      // Required: Path to the image you want to watermark
8      imagePath: path.join(__dirname, './photo.jpg'),
9      
10      // Required: Allowed referrers for CORS
11      allowedReferrers: ['http://localhost:3000', 'https://mywebsite.com'],
12      
13      // Required: Headers for API calls
14      headers: {
15        host: 'localhost:3000',
16        connection: 'keep-alive',
17        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
18        referer: req.headers.referer || '',
19        cookie: req.headers.cookie || ''
20      },
21      
22      // Optional: Text watermark
23      textWatermark: '© 2025 My Photography Studio',
24      textColor: '#ffffff',
25      opacity: '0.8',
26      fontWeight: '800',
27      fontFamily: 'Inter, Arial, sans-serif'
28    });
29    
30    res.setHeader('Content-Type', 'image/png');
31    return res.send(watermarkedImage);
32  } catch (error) {
33    console.error('Error adding text watermark:', error);
34    res.status(500).send('An error occurred while processing the image.');
35  }
36}

Real-World Use Cases

Batch Processing

Process multiple images at once with consistent watermarks

Intermediate
Perfect for galleries and portfolios
batch-processing.js
1const { multiImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function batchWatermarkImages(req, res) {
5  try {
6    const watermarkedImages = await multiImageWatermark({
7      // Required: Array of image paths to process
8      imagePaths: [
9        path.join(__dirname, './gallery/image1.jpg'),
10        path.join(__dirname, './gallery/image2.jpg'),
11        path.join(__dirname, './gallery/image3.jpg'),
12        path.join(__dirname, './gallery/image4.jpg')
13      ],
14      
15      // Optional: Path to the watermark image (logo)
16      watermarkPath: path.join(__dirname, './brand-logo.png'),
17      
18      // Required: Allowed referrers for CORS
19      allowedReferrers: ['http://localhost:3000', 'https://myportfolio.com'],
20      
21      // Required: Headers for API calls
22      headers: {
23        host: 'localhost:3000',
24        connection: 'keep-alive',
25        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
26        referer: req.headers.referer || '',
27        cookie: req.headers.cookie || ''
28      },
29      
30      // Optional: Text watermark
31      textWatermark: '© 2025 Professional Photography',
32      textColor: '#ffffff',
33      opacity: '0.7',
34      fontWeight: '600',
35      fontFamily: 'Inter, Arial, sans-serif'
36    });
37    
38    // Returns array of watermarked images
39    return res.json({
40      success: true,
41      count: watermarkedImages.length,
42      images: watermarkedImages
43    });
44  } catch (error) {
45    console.error('Error in batch processing:', error);
46    res.status(500).json({ error: 'An error occurred while processing the images.' });
47  }
48}

E-commerce Product Protection

Protect product images while maintaining brand visibility

Intermediate
E-commerce and marketplace applications
ecommerce-watermark.js
1const { singleImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function addEcommerceWatermark(req, res) {
5  try {
6    const { productId, imagePath } = req.body;
7    
8    const watermarkedImage = await singleImageWatermark({
9      // Required: Path to the product image
10      imagePath: path.join(__dirname, imagePath),
11      
12      // Optional: Brand logo watermark
13      watermarkPath: path.join(__dirname, './brand-logo.png'),
14      
15      // Required: Allowed referrers for CORS
16      allowedReferrers: [
17        'http://localhost:3000',
18        'https://myecommerce.com',
19        'https://admin.myecommerce.com'
20      ],
21      
22      // Required: Headers for API calls
23      headers: {
24        host: 'localhost:3000',
25        connection: 'keep-alive',
26        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
27        referer: req.headers.referer || '',
28        cookie: req.headers.cookie || ''
29      },
30      
31      // Optional: Text watermark for product protection
32      textWatermark: 'PROTECTED',
33      textColor: '#ff6b6b',
34      opacity: '0.4',
35      fontWeight: '800',
36      fontFamily: 'Arial Black, sans-serif',
37      
38      // Optional: App name for branding
39      appName: 'MyEcommerce'
40    });
41    
42    res.setHeader('Content-Type', 'image/png');
43    return res.send(watermarkedImage);
44  } catch (error) {
45    console.error('Error adding ecommerce watermark:', error);
46    res.status(500).json({ error: 'An error occurred while processing the image.' });
47  }
48}

Social Media Branding

Add your social media handle to images for brand recognition

Beginner
Social media marketing and content creation
social-media-watermark.js
1const { singleImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function addSocialMediaWatermark(req, res) {
5  try {
6    const watermarkedImage = await singleImageWatermark({
7      // Required: Path to the social media image
8      imagePath: path.join(__dirname, './social-post.jpg'),
9      
10      // Required: Allowed referrers for CORS
11      allowedReferrers: [
12        'http://localhost:3000',
13        'https://myapp.com',
14        'https://instagram.com',
15        'https://facebook.com'
16      ],
17      
18      // Required: Headers for API calls
19      headers: {
20        host: 'localhost:3000',
21        connection: 'keep-alive',
22        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
23        referer: req.headers.referer || '',
24        cookie: req.headers.cookie || ''
25      },
26      
27      // Optional: Social media handle as watermark
28      textWatermark: '@mybrand',
29      textColor: '#ffffff',
30      opacity: '0.9',
31      fontWeight: '700',
32      fontFamily: 'Inter, Arial, sans-serif',
33      
34      // Optional: App name
35      appName: 'MySocialApp'
36    });
37    
38    res.setHeader('Content-Type', 'image/png');
39    return res.send(watermarkedImage);
40  } catch (error) {
41    console.error('Error adding social media watermark:', error);
42    res.status(500).send('An error occurred while processing the image.');
43  }
44}

Document Security

Add confidential watermarks to sensitive documents

Intermediate
Corporate and legal document protection
document-watermark.js
1const { singleImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function addDocumentWatermark(req, res) {
5  try {
6    const watermarkedImage = await singleImageWatermark({
7      // Required: Path to the document image
8      imagePath: path.join(__dirname, './document.pdf.jpg'),
9      
10      // Required: Allowed referrers for CORS
11      allowedReferrers: [
12        'http://localhost:3000',
13        'https://mycompany.com',
14        'https://internal.mycompany.com'
15      ],
16      
17      // Required: Headers for API calls
18      headers: {
19        host: 'localhost:3000',
20        connection: 'keep-alive',
21        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
22        referer: req.headers.referer || '',
23        cookie: req.headers.cookie || ''
24      },
25      
26      // Optional: Confidential text watermark
27      textWatermark: 'CONFIDENTIAL - INTERNAL USE ONLY',
28      textColor: '#ff0000',
29      opacity: '0.2',
30      fontWeight: '800',
31      fontFamily: 'Arial Black, sans-serif',
32      
33      // Optional: Company name
34      appName: 'MyCompany'
35    });
36    
37    res.setHeader('Content-Type', 'image/png');
38    return res.send(watermarkedImage);
39  } catch (error) {
40    console.error('Error adding document watermark:', error);
41    res.status(500).send('An error occurred while processing the image.');
42  }
43}

Advanced Examples

Robust Error Handling

Production-ready error handling with detailed error codes

Advanced
Production applications with comprehensive error handling
error-handling.js
1const { singleImageWatermark } = require('images-watermark');
2const path = require('path');
3
4async function safeWatermarkOperation(req, res) {
5  try {
6    // Validate required parameters
7    const { imagePath, watermarkPath, textWatermark, allowedReferrers } = req.body;
8    
9    if (!imagePath) {
10      return res.status(400).json({ 
11        error: 'Image path is required',
12        code: 'MISSING_IMAGE_PATH'
13      });
14    }
15    
16    if (!allowedReferrers || !Array.isArray(allowedReferrers) || allowedReferrers.length === 0) {
17      return res.status(400).json({ 
18        error: 'Allowed referrers array is required',
19        code: 'MISSING_REFERRERS'
20      });
21    }
22    
23    // Check if image file exists
24    const fs = require('fs');
25    if (!fs.existsSync(imagePath)) {
26      return res.status(404).json({ 
27        error: 'Image file not found',
28        code: 'IMAGE_NOT_FOUND',
29        path: imagePath
30      });
31    }
32    
33    // Check if watermark file exists (if provided)
34    if (watermarkPath && !fs.existsSync(watermarkPath)) {
35      return res.status(404).json({ 
36        error: 'Watermark file not found',
37        code: 'WATERMARK_NOT_FOUND',
38        path: watermarkPath
39      });
40    }
41    
42    const watermarkedImage = await singleImageWatermark({
43      imagePath: path.resolve(imagePath),
44      watermarkPath: watermarkPath ? path.resolve(watermarkPath) : undefined,
45      allowedReferrers,
46      headers: {
47        host: req.headers.host || 'localhost:3000',
48        connection: 'keep-alive',
49        'user-agent': req.headers['user-agent'] || 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
50        referer: req.headers.referer || '',
51        cookie: req.headers.cookie || ''
52      },
53      textWatermark: textWatermark || undefined,
54      textColor: '#ffffff',
55      opacity: '0.8',
56      fontWeight: '600',
57      fontFamily: 'Inter, Arial, sans-serif'
58    });
59    
60    res.setHeader('Content-Type', 'image/png');
61    return res.send(watermarkedImage);
62  } catch (error) {
63    console.error('Error in watermark operation:', error);
64    
65    // Handle specific error types
66    if (error.code === 'ENOENT') {
67      return res.status(404).json({ 
68        error: 'File not found',
69        code: 'FILE_NOT_FOUND'
70      });
71    }
72    
73    if (error.message.includes('allowedReferrers')) {
74      return res.status(400).json({ 
75        error: 'Invalid referrer configuration',
76        code: 'INVALID_REFERRER'
77      });
78    }
79    
80    res.status(500).json({ 
81      error: 'An error occurred while processing the image',
82      code: 'PROCESSING_ERROR'
83    });
84  }
85}

Express.js Middleware

Create reusable middleware for automatic watermarking

Advanced
Web applications with automatic watermarking
express-middleware.js
1const express = require('express');
2const { singleImageWatermark } = require('images-watermark');
3const path = require('path');
4
5const app = express();
6app.use(express.json());
7
8// Middleware to add watermarks to images
9const watermarkMiddleware = (options = {}) => {
10  return async (req, res, next) => {
11    try {
12      // Skip watermarking for allowed referrers
13      const referer = req.headers.referer || '';
14      const allowedReferrers = options.allowedReferrers || ['http://localhost:3000'];
15      
16      const isAllowedReferrer = allowedReferrers.some(r => 
17        referer.includes(r.replace(/^https?:\/\//, ''))
18      );
19      
20      if (isAllowedReferrer) {
21        return next(); // Skip watermarking for allowed referrers
22      }
23      
24      // Add watermark for direct access
25      const imagePath = req.params.imagePath || req.query.image;
26      if (!imagePath) {
27        return res.status(400).json({ error: 'Image path required' });
28      }
29      
30      const watermarkedImage = await singleImageWatermark({
31        imagePath: path.join(__dirname, 'public', imagePath),
32        allowedReferrers,
33        headers: {
34          host: req.headers.host || 'localhost:3000',
35          connection: 'keep-alive',
36          'user-agent': req.headers['user-agent'] || 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
37          referer: referer,
38          cookie: req.headers.cookie || ''
39        },
40        textWatermark: options.textWatermark || '© My Brand',
41        textColor: options.textColor || '#ffffff',
42        opacity: options.opacity || '0.8',
43        fontWeight: options.fontWeight || '600'
44      });
45      
46      res.setHeader('Content-Type', 'image/png');
47      res.send(watermarkedImage);
48    } catch (error) {
49      console.error('Watermark middleware error:', error);
50      next(error);
51    }
52  };
53};
54
55// Usage
56app.get('/images/:imagePath', watermarkMiddleware({
57  allowedReferrers: ['https://mywebsite.com', 'https://admin.mywebsite.com'],
58  textWatermark: '© 2025 My Brand',
59  textColor: '#ffffff',
60  opacity: '0.7'
61}));
62
63app.listen(3000, () => {
64  console.log('Server running on port 3000');
65});

Best Practices & Tips

Performance Optimization

  • • Use appropriate opacity levels (0.3-0.8) for readability
  • • Leverage the built-in caching for repeated watermarks
  • • Process images in batches for better performance
  • • Use PNG watermarks for transparency support

Security & Access Control

  • • Configure allowedReferrers for proper access control
  • • Use different watermark settings for different domains
  • • Implement proper error handling for production
  • • Validate file paths and permissions

Design & Branding

  • • Choose colors that contrast well with your images
  • • Use consistent font families across your brand
  • • Test watermarks on different image backgrounds
  • • Balance visibility with aesthetics

File Management

  • • Organize watermark assets in a dedicated folder
  • • Use descriptive file names for different watermarks
  • • Implement backup strategies for original images
  • • Monitor disk space for batch processing

Ready to Get Started?

Install the package and start protecting your images today

npm install images-watermarkView Documentation