npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2026 – Pkg Stats / Ryan Hefner

@alkemic/logger-nextjs

v0.1.10

Published

🚧 Sorry folks! This library is currently built for our internal services only. But don’t worry β€” we’re planning to release a public version in the future! πŸŽ‰

Readme

@alkemic/logger-nextjs

🚧 Sorry folks! This library is currently built for our internal services only. But don’t worry β€” we’re planning to release a public version in the future! πŸŽ‰

⚑️ Powered by Pino and Winston, this logger runs smoothly on both the server 🌐 and client πŸ’» sides β€” no need to choose sides, it plays nice everywhere! 😎

πŸ“š Table of Contents

πŸ“¦ Installation

npm install @alkemic/logger-nextjs

οΏ½ Quick Start

  1. Create a shared logger using createLogger() in a module like lib/logger.ts and export it for reuse.
  2. Derive contextual child loggers with logger.child({ ...metadata }) inside API handlers, React components, and edge middleware.
  3. Tune runtime behavior by setting the environment variables documented in βš™οΈ Configuration before booting your app.
  4. Validate the setup by running npm test, which exercises Winston, Pino, and environment-specific flows end to end.

πŸ“– Usage Examples

Basic Setup

// lib/logger.ts
import { createLogger } from '@alkemic/logger-nextjs';

export const logger = await createLogger();

Server-side Usage

// app/api/users/route.ts
import { logger } from '@/lib/logger';

export async function GET() {
    const requestLogger = logger.child({ 
        module: 'users-api',
        requestId: crypto.randomUUID()
    });
    
    requestLogger.info('Starting user list retrieval');
    
    try {
        const users = await fetchUsers();
        requestLogger.info('User retrieval completed', { count: users.length });
        return Response.json(users);
    } catch (error) {
        requestLogger.error('User retrieval failed', error);
        return Response.json({ error: 'Server error' }, { status: 500 });
    }
}

Client-side Usage

// components/LoginForm.tsx
"use client"
import { logger } from '@/lib/logger';
import { useState } from 'react';

export default function LoginForm() {
    const [loading, setLoading] = useState(false);
    const formLogger = logger.child({ component: 'LoginForm' });

    const handleSubmit = async (formData: FormData) => {
        formLogger.info('Login attempt started');
        setLoading(true);
        
        try {
            // Sensitive data is automatically masked
            formLogger.debug('Login request data', {
                username: formData.get('username'),
                password: formData.get('password'), // Masked as [REDACTED]
                timestamp: new Date().toISOString()
            });
            
            const result = await fetch('/api/auth/login', {
                method: 'POST',
                body: formData
            });
            
            if (result.ok) {
                formLogger.info('Login successful');
            } else {
                formLogger.warn('Login failed', { status: result.status });
            }
        } catch (error) {
            formLogger.error('Login error', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <form action={handleSubmit}>
            {/* form fields */}
        </form>
    );
}

Edge Runtime Usage

// middleware.ts
import { logger } from '@/lib/logger';
import { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
    const middlewareLogger = logger.child({ 
        middleware: 'auth',
        path: request.nextUrl.pathname 
    });
    
    // Edge Runtime outputs in Pino JSON format
    middlewareLogger.info('Middleware execution', {
        method: request.method,
        userAgent: request.headers.get('user-agent')
    });
    
    return NextResponse.next();
}

πŸ§ͺ Testing

# Run the full matrix (production β†’ development β†’ verbose β†’ edge β†’ winston features)
npm test

# Individual test execution
npm run test:prod       # Production environment test (info level and above)
npm run test:dev        # Development environment test (debug level enabled)
npm run test:verbose    # Verbose level test (shows all logs)
npm run test:edge       # Edge Runtime test (Pino JSON output)
npm run test:winston-features  # Winston advanced features test

πŸ“‹ Test Coverage

| File | Description | |------|-------------| | basic.test.ts | βœ… Basic log level testing (verbose, debug, info, warn, error, fatal)βœ… Child logger creation and nesting testsβœ… Error handling and stack trace testsβœ… Verbose level detailed testsβœ… Environment variable combination tests (SERVER_ENV, LOG_LEVEL) | | edge.test.ts | βœ… Pino JSON output format validationβœ… Edge Runtime environment detectionβœ… UTF-8 encoding support | | winston-features.test.ts | βœ… File logging (daily logs saved in logs/ folder)βœ… Sensitive data masking ([REDACTED] processing)βœ… Single-line/multi-line object output formatsβœ… Large dataset processingβœ… Nested object and array sensitive data masking |

πŸ”§ Environment Variables

Environment variables supported in testing and actual usage:

| Variable | Values | Description | |----------|--------|-------------| | SERVER_ENV | development | production | Adjusts log levels based on the environment. | | LOG_LEVEL | verbose | debug | info | warn | error | fatal | Sets the minimum log level to output. | | NEXT_RUNTIME | edge | Triggers the Pino logger for Edge Runtime. | | LOG_USE_FILE | true | false | Enables or disables logging to daily rotated files (Winston only). | | LOG_SENSITIVE_KEYS | Comma-separated string | Specifies keys to mask (e.g., password,secret,token). | | LOG_USE_SINGLE_LINE_OBJ | true | false | Toggles between single-line and multi-line object logging (Winston only). |

🧰 Scripts

| Script | Description | |--------|-------------| | npm run build | Cleans the lib/ folder, compiles TypeScript, and rewrites path aliases with tsc-alias. | | npm run watch | Rebuilds continuously via tsc-watch and re-applies tsc-alias on each successful compilation. | | npm run clean | Removes all build artifacts under lib/. | | npm test | Executes the full test matrix (test:prod β†’ test:dev β†’ test:verbose β†’ test:edge β†’ test:winston-features). | | npm run test:prod | Runs basic.test.ts with SERVER_ENV=production. | | npm run test:dev | Runs basic.test.ts with SERVER_ENV=development. | | npm run test:verbose | Runs basic.test.ts with verbose logging enabled. | | npm run test:edge | Runs edge.test.ts with NEXT_RUNTIME=edge to validate the Pino setup. | | npm run test:winston-features | Runs winston-features.test.ts focusing on file logging, masking, and formatting. |

βš™οΈ Configuration

Environment Variables Setup

# .env.local (Next.js)
SERVER_ENV=development
LOG_LEVEL=debug
LOG_USE_FILE=true
LOG_SENSITIVE_KEYS=password,secret,token,apiKey,authorization
LOG_USE_SINGLE_LINE_OBJ=false

Winston File Logging

When file logging is enabled, daily log files are created in the logs/ folder:

logs/
β”œβ”€β”€ 2025-09-28-00.log  # Logs from 00:00~23:59
β”œβ”€β”€ 2025-09-28-01.log
└── ...

Sensitive Data Masking

The following keys are automatically masked as [REDACTED]:

// Default sensitive keys
const defaultSensitiveKeys = ['password', 'secret', 'token', 'apiKey'];

// Additional configuration via environment variables
LOG_SENSITIVE_KEYS=password,secret,token,apiKey,authorization

// Recursive masking for nested objects and arrays
logger.info('User data', {
    users: [
        { id: 1, name: 'User1', password: 'secret123' }, // password: '[REDACTED]'
        { id: 2, name: 'User2', token: 'jwt-token' }     // token: '[REDACTED]'
    ]
});

Character Encoding Issues

If you see garbled characters in PowerShell:

# Set PowerShell UTF-8 encoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# Then run tests
npm test

✨ Features

🌍 Universal Compatibility

  • Node.js Server: Winston-based formatted text output
  • Edge Runtime: Pino-based high-performance JSON output
  • Browser: Pino-based JSON output

πŸ”§ Advanced Architecture

  • Adapter Pattern: Unified Logger interface for both Winston and Pino
  • Fatal Level Support: Complete support for fatal(60) log level in Winston
  • Stack Trace Preservation: Direct method binding for accurate call site tracking
  • TypeScript-first API: Published with .d.ts definitions for strong typing in editors and builds

πŸ”— Child Logger System

  • Context Binding: Trackable logs with logger.child({ requestId, module })
  • Nested Child Support: Create child loggers from existing child loggers
  • Metadata Inheritance: Automatic inheritance of parent metadata

πŸ›‘οΈ Winston Advanced Features

  • πŸ“ File Logging: Automatic daily log file generation and rotation
  • πŸ”’ Sensitive Data Masking: Auto [REDACTED] for password, token, secret, etc.
  • πŸ“„ Output Format Control: Single-line or multi-line object output
  • πŸ” Recursive Masking: Masks sensitive data within nested objects and arrays

πŸ“‹ Log Levels

| Level | Priority | Usage | Example | |-------|----------|-------|---------| | verbose | 1 | Most detailed debug information | Function entry/exit, variable values | | debug | 2 | Development stage debugging | Information needed only in dev environment | | info | 3 | General application information | User actions, API requests | | warn | 4 | Warning messages | Deprecated API usage | | error | 5 | Error occurrences | Exception handling, failed operations | | fatal | 6 | Critical errors | Application termination level |

🌍 Environment-based Log Levels

  • development: Shows debug level and above
  • production: Shows info level and above
  • verbose setting: Shows all levels

πŸ—οΈ Architecture

Adapter Pattern Implementation

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚           createLogger()            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ Environment Check β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
              β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚ NEXT_RUNTIME ?  β”‚
     β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
           β”‚     β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β” β”Œβ–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚  edge   β”‚ β”‚ nodejs    β”‚
    β”‚         β”‚ β”‚           β”‚
    β”‚  Pino   β”‚ β”‚ Winston   β”‚
    β”‚  JSON   β”‚ β”‚ Formatted β”‚
    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”˜ β””β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚     β”‚
           └─────▼─────┐
           β”‚ AdapterLogger β”‚
           β”‚             β”‚
           β”‚ - verbose() β”‚
           β”‚ - debug()   β”‚
           β”‚ - info()    β”‚
           β”‚ - warn()    β”‚
           β”‚ - error()   β”‚
           β”‚ - fatal()   β”‚
           β”‚ - child()   β”‚
           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

File Structure

src/
β”œβ”€β”€ index.ts              # Main entry point
β”œβ”€β”€ defs.ts              # Type definitions and Winston configuration
β”œβ”€β”€ adapter-logger.ts    # Unified adapter class
β”œβ”€β”€ winston-server.ts    # Winston server factory
β”œβ”€β”€ winston-formats.ts   # Winston formatter and sensitive data masking
β”œβ”€β”€ pino-edge.ts         # Pino Edge Runtime factory
└── pino-browser.ts      # Pino browser factory

tests/
β”œβ”€β”€ basic.test.ts           # Basic functionality + environment variable tests
β”œβ”€β”€ edge.test.ts           # Edge Runtime specific tests
└── winston-features.test.ts # Winston advanced feature tests