Author: saqibkhan

  • Dynamic Origin Handling

    You might want to dynamically determine whether to allow a request based on the origin. Here’s an example that allows origins based on a list or pattern:

    const allowedOrigins = ['http://example.com', 'http://another-example.com'];
    
    const corsOptions = {
      origin: (origin, callback) => {
    
    if (allowedOrigins.includes(origin) || !origin) { // Handle no origin (e.g., CURL requests)
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
    }, methods: 'GET,POST,PUT,DELETE,OPTIONS', allowedHeaders: 'Content-Type,Authorization', credentials: true, }; app.use(cors(corsOptions));
  • Using CORS in Other Frameworks

    If you are not using Express but another framework or no framework at all, you might need to handle CORS manually or use specific middleware. The general idea is similar: set appropriate headers in your HTTP responses.

  • Advanced Configuration

    For more complex scenarios, like allowing multiple origins, you can use a function for the origin option:

    const corsOptions = {
      origin: (origin, callback) => {
    
    if (['http://example.com', 'http://another-example.com'].includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
    }, methods: 'GET,POST', allowedHeaders: 'Content-Type,Authorization', }; app.use(cors(corsOptions));
  • Handling Preflight Requests

    Browsers send preflight requests (OPTIONS requests) to check if the server allows the actual request. The cors middleware handles this for you, but if you need more control, you can set up custom handling:

    app.options('*', cors(corsOptions)); // Pre-flight requests
    
  • Configuring CORS

    You can configure CORS to be more specific about which origins are allowed and other settings. For example:

    const corsOptions = {
      origin: 'http://example.com', // Allow only requests from this origin
      methods: 'GET,POST', // Allow only GET and POST methods
      allowedHeaders: 'Content-Type,Authorization', // Allow only these headers
    };
    
    app.use(cors(corsOptions));
    
  • Use cors in Your Express Application

    If you are using Express, you can set up CORS by including the cors middleware in your application. Here’s a basic example:

    const express = require('express');
    const cors = require('cors');
    
    const app = express();
    
    // Enable CORS for all origins
    app.use(cors());
    
    // Your routes here
    app.get('/', (req, res) => {
      res.send('Hello, world!');
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(Server running on port ${PORT});
    });
    
  • Install the cors package

    First, you need to install the cors package. You can do this using npm or yarn:

    npm install cors
    

    or

    yarn add cors
    
  • Log Enrichment

    Enrich logs with additional context or metadata. For example, you might add user-specific information or request context.

    const winston = require('winston');
    
    const requestLogger = winston.createLogger({
      level: 'info',
      format: winston.format.combine(
    
    winston.format.timestamp(),
    winston.format.json(),
    winston.format.printf(({ level, message, timestamp, requestId }) => {
      return ${timestamp} [${level}] [RequestId: ${requestId}] ${message};
    })
    ), transports: [
    new winston.transports.Console()
    ] }); // Middleware to attach requestId app.use((req, res, next) => { req.requestId = Math.random().toString(36).substring(2); next(); }); // Log with requestId app.get('/', (req, res) => { requestLogger.info('Handled request', { requestId: req.requestId }); res.send('Hello World!'); });
  • Integration with External Services

    Elasticsearch Integration

    Elasticsearch is commonly used for log storage and search. To integrate Winston with Elasticsearch, you can use the winston-elasticsearch transport.

    1. Install the Transport:
    npm install winston-elasticsearch
    1. Configure the Transport:
    const winston = require('winston'); const ElasticsearchTransport = require('winston-elasticsearch'); const client = new ElasticsearchTransport.Client({ node: 'http://localhost:9200' }); const transport = new ElasticsearchTransport({ level: 'info', client: client, indexPrefix: 'logs', transformer: (log) => ({ message: log.message, level: log.level, timestamp: log.timestamp }) }); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ transport ] }); logger.info('Log message sent to Elasticsearch');
    Cloud Logging Services

    For cloud-based logging solutions like AWS CloudWatch or Google Cloud Logging:

    • AWS CloudWatch:
    npm install winston-cloudwatch
    const winston = require('winston'); const CloudWatchTransport = require('winston-cloudwatch'); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ new CloudWatchTransport({ logGroupName: 'my-log-group', logStreamName: 'my-log-stream', awsRegion: 'us-east-1' }) ] }); logger.info('Log message sent to CloudWatch');
    • Google Cloud Logging:
    npm install @google-cloud/logging-winston javascriptCopy codeconst winston = require('winston'); const { LoggingWinston } = require('@google-cloud/logging-winston'); const loggingWinston = new LoggingWinston(); const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.json() ), transports: [ loggingWinston ] }); logger.info('Log message sent to Google Cloud Logging');
  • Log Filtering

    To filter logs based on criteria, you can use custom log formats or transports.

    const winston = require('winston');
    
    const filterTransport = new winston.transports.Console({
      format: winston.format((info) => {
    
    if (info.level === 'error') {
      return info;
    }
    })() }); const logger = winston.createLogger({ level: 'info', format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
    ), transports: [filterTransport] }); logger.info('This will not appear'); logger.error('This is an error message');