This page documents all exported functions, types, and interfaces in vij-sdk.
Functions
init()
Initialize the VIJ SDK with configuration options. Must be called before using other SDK functions.
init ( options : InitOptions ): void
Example :
import { init } from "vij-sdk" ;
init ({
endpoint: "https://vij.example.com/api/logs" ,
appId: "my-app" ,
environment: "production" ,
batch: true ,
maxBatchSize: 20 ,
flushIntervalMs: 5000 ,
maxQueueSize: 100 ,
metadata: {
version: "1.0.0"
}
});
Call init() once at application startup, before any other VIJ functions. Calling it multiple times will reinitialize the SDK and may cause data loss.
captureException()
Capture and send an error to VIJ Admin.
captureException (
error : Error ,
metadata ?: Record < string , any > ,
severity ?: Severity
): void
The error object to capture. Must have name, message, and stack properties.
Optional metadata to attach to this error. Merged with global metadata from init().
Severity level: "error", "warning", or "info".
Example :
import { captureException } from "vij-sdk" ;
try {
throw new Error ( "Payment processing failed" );
} catch ( error ) {
captureException ( error , {
userId: "user-123" ,
orderId: "order-456" ,
amount: 99.99
}, "error" );
}
Returns : void
captureMessage()
Capture and send a custom log message to VIJ Admin.
captureMessage (
message : string ,
metadata ?: Record < string , any > ,
severity ?: Severity
): void
The log message to capture.
Optional metadata to attach to this message.
Severity level: "error", "warning", or "info".
Example :
import { captureMessage } from "vij-sdk" ;
captureMessage ( "User logged in" , {
userId: "user-123" ,
loginMethod: "oauth" ,
timestamp: Date . now ()
}, "info" );
Returns : void
flush()
Immediately flush all queued logs to the server, bypassing batch settings.
Example :
import { flush } from "vij-sdk" ;
// Ensure all logs are sent before page unload
window . addEventListener ( "beforeunload" , async () => {
await flush ();
});
Returns : Promise<void> - Resolves when all logs are sent
Useful for ensuring logs are sent before page navigation, process exit, or application shutdown.
Update global metadata that will be attached to all future logs.
setMetadata ( metadata : Record < string , any > ): void
metadata
Record<string, any>
required
Metadata object to merge with existing global metadata.
Example :
import { setMetadata } from "vij-sdk" ;
// Set initial metadata
init ({
endpoint: "..." ,
appId: "..." ,
environment: "production" ,
metadata: { version: "1.0.0" }
});
// Update metadata after user login
function onUserLogin ( user ) {
setMetadata ({
userId: user . id ,
userEmail: user . email ,
userPlan: user . plan
});
}
// All subsequent logs will include user information
Returns : void
Metadata set via setMetadata() is merged with metadata passed to init(). Later values override earlier ones.
Remove specific keys from global metadata.
clearMetadata ( keys : string []): void
Array of metadata keys to remove.
Example :
import { setMetadata , clearMetadata } from "vij-sdk" ;
// Set user metadata on login
setMetadata ({ userId: "user-123" , userEmail: "user@example.com" });
// Clear user metadata on logout
clearMetadata ([ "userId" , "userEmail" ]);
Returns : void
Retrieve the current global metadata object.
getMetadata (): Record < string , any >
Example :
import { getMetadata } from "vij-sdk" ;
const currentMetadata = getMetadata ();
console . log ( currentMetadata );
// { version: "1.0.0", userId: "user-123" }
Returns : Record<string, any> - Current global metadata
Types
InitOptions
Configuration options for the init() function.
interface InitOptions {
endpoint : string ;
appId : string ;
environment : string ;
batch ?: boolean ;
maxBatchSize ?: number ;
flushIntervalMs ?: number ;
maxQueueSize ?: number ;
metadata ?: Record < string , any >;
}
VIJ Admin API endpoint URL (e.g., https://vij.example.com/api/logs)
Unique identifier for your application
Environment name (e.g., production, staging, development)
Maximum logs per batch (1-100)
Batch flush interval in milliseconds (1000-60000)
Maximum queue size before dropping old logs (10-1000)
metadata
Record<string, any>
default: "{}"
Global metadata attached to all logs
Example :
import { type InitOptions } from "vij-sdk" ;
const config : InitOptions = {
endpoint: process . env . VIJ_ENDPOINT ! ,
appId: "my-app" ,
environment: process . env . NODE_ENV ,
batch: true ,
maxBatchSize: 20 ,
flushIntervalMs: 5000 ,
maxQueueSize: 100 ,
metadata: {
version: "1.0.0" ,
region: "us-east-1"
}
};
Severity
Severity level for errors and messages.
type Severity = "error" | "warning" | "info" ;
Values :
"error" - Critical errors requiring immediate attention
"warning" - Non-critical issues that should be investigated
"info" - Informational logs for tracking behavior
Example :
import { captureException , type Severity } from "vij-sdk" ;
function logError ( error : Error , level : Severity ) {
captureException ( error , {}, level );
}
logError ( new Error ( "Critical failure" ), "error" );
logError ( new Error ( "Deprecated API used" ), "warning" );
LogEntry
Structure of a log entry sent to VIJ Admin.
interface LogEntry {
message : string ;
name : string ;
stack : string ;
severity : Severity ;
timestamp : string ;
appId : string ;
environment : string ;
metadata : Record < string , any >;
context : BrowserContext | NodeContext ;
}
Error message or custom log message
Error name (e.g., Error, TypeError, CustomError)
Severity level: error, warning, or info
ISO 8601 timestamp when the error was captured
Application identifier from init()
Environment name from init()
Merged global and per-error metadata
context
BrowserContext | NodeContext
Automatically collected contextual information
You don’t create LogEntry objects directly. The SDK generates them automatically when you call captureException() or captureMessage().
BrowserContext
Contextual information collected in browser environments.
interface BrowserContext {
viewport : {
width : number ;
height : number ;
};
screen : {
width : number ;
height : number ;
colorDepth : number ;
};
browser : {
userAgent : string ;
language : string ;
platform : string ;
cookieEnabled : boolean ;
doNotTrack : string | null ;
};
network ?: {
effectiveType : string ;
downlink : number ;
rtt : number ;
};
}
Example :
{
"viewport" : { "width" : 1920 , "height" : 1080 },
"screen" : { "width" : 1920 , "height" : 1080 , "colorDepth" : 24 },
"browser" : {
"userAgent" : "Mozilla/5.0..." ,
"language" : "en-US" ,
"platform" : "MacIntel" ,
"cookieEnabled" : true ,
"doNotTrack" : "1"
},
"network" : {
"effectiveType" : "4g" ,
"downlink" : 10 ,
"rtt" : 50
}
}
NodeContext
Contextual information collected in Node.js environments.
interface NodeContext {
process : {
pid : number ;
platform : string ;
arch : string ;
nodeVersion : string ;
uptime : number ;
memory : {
rss : number ;
heapTotal : number ;
heapUsed : number ;
external : number ;
};
};
}
Example :
{
"process" : {
"pid" : 12345 ,
"platform" : "linux" ,
"arch" : "x64" ,
"nodeVersion" : "v20.0.0" ,
"uptime" : 3600 ,
"memory" : {
"rss" : 50000000 ,
"heapTotal" : 30000000 ,
"heapUsed" : 20000000 ,
"external" : 1000000
}
}
}
Advanced Usage
Manual Queue Management
import { captureException , flush } from "vij-sdk" ;
// Capture errors
captureException ( error1 , { feature: "checkout" });
captureException ( error2 , { feature: "payment" });
// Manually flush queue before critical operation
await flush ();
// Continue with critical operation
await criticalOperation ();
import { setMetadata , clearMetadata , captureException } from "vij-sdk" ;
// User logs in
function onLogin ( user ) {
setMetadata ({
userId: user . id ,
userEmail: user . email ,
userRole: user . role ,
loginTime: new Date (). toISOString ()
});
}
// User logs out
function onLogout () {
clearMetadata ([ "userId" , "userEmail" , "userRole" , "loginTime" ]);
}
// Feature flag changes
function onFeatureFlagChange ( flags ) {
setMetadata ({ featureFlags: flags });
}
TypeScript Integration
import {
init ,
captureException ,
captureMessage ,
type InitOptions ,
type Severity ,
type LogEntry
} from "vij-sdk" ;
// Type-safe configuration
const config : InitOptions = {
endpoint: process . env . VIJ_ENDPOINT ! ,
appId: "my-ts-app" ,
environment: process . env . NODE_ENV as string ,
batch: true ,
maxBatchSize: 20 ,
metadata: {
version: "1.0.0"
}
};
init ( config );
// Type-safe error capture
function handleError ( error : Error , severity : Severity = "error" ) {
captureException ( error , {
timestamp: new Date (). toISOString (),
handled: true
}, severity );
}
// Custom error class
class ValidationError extends Error {
constructor (
message : string ,
public field : string ,
public value : any
) {
super ( message );
this . name = "ValidationError" ;
}
}
try {
throw new ValidationError ( "Invalid email" , "email" , "invalid@" );
} catch ( error ) {
if ( error instanceof ValidationError ) {
captureException ( error , {
field: error . field ,
value: error . value
}, "warning" );
}
}
React Integration
import { captureException , setMetadata } from "vij-sdk" ;
import { useEffect } from "react" ;
function App () {
useEffect (() => {
// Update metadata when user changes
setMetadata ({
userId: currentUser ?. id ,
userRole: currentUser ?. role
});
}, [ currentUser ]);
return < YourApp />;
}
// Error boundary
class ErrorBoundary extends React . Component {
componentDidCatch ( error : Error , errorInfo : React . ErrorInfo ) {
captureException ( error , {
componentStack: errorInfo . componentStack ,
route: window . location . pathname
});
}
render () {
return this . props . children ;
}
}
Express Integration
import express from "express" ;
import { captureException , setMetadata } from "vij-sdk" ;
const app = express ();
// Attach request context to all errors
app . use (( req , res , next ) => {
res . locals . requestId = generateRequestId ();
next ();
});
// Error handler
app . use (( err : Error , req : express . Request , res : express . Response , next : express . NextFunction ) => {
captureException ( err , {
requestId: res . locals . requestId ,
url: req . originalUrl ,
method: req . method ,
userId: req . user ?. id ,
ip: req . ip
});
res . status ( 500 ). json ({ error: "Internal server error" });
});
Best Practices
Initialize once at startup
Call init() once when your application starts, before any other code: // Good - at app entry point
import { init } from "vij-sdk" ;
init ({ /* config */ });
// Then start your app
startApp ();
Use TypeScript for type safety
Import types for better IDE support and compile-time checking: import { init , type InitOptions , type Severity } from "vij-sdk" ;
const config : InitOptions = { /* ... */ };
const level : Severity = "error" ;
Flush before critical operations
Ensure logs are sent before page unload, process exit, or deployments: window . addEventListener ( "beforeunload" , () => flush ());
process . on ( "SIGTERM" , async () => {
await flush ();
process . exit ( 0 );
});
Use metadata for context, not in messages
// Good
captureMessage ( "Payment failed" , { orderId: 123 , amount: 99.99 });
// Bad
captureMessage ( `Payment failed for order 123 with amount 99.99` );
Next Steps