· 13 Min read

Getting Started with Bun 1.2: Complete Setup Guide

Getting Started with Bun 1.2: Complete Setup Guide

JavaScript development has evolved dramatically in recent years, and Bun has emerged as a game-changing runtime that promises to revolutionize how we build, test, and deploy applications. With the release of Bun 1.2 in January 2025, developers now have access to an incredibly fast, all-in-one toolkit that combines a JavaScript runtime, package manager, test runner, and bundler into a single executable.

This comprehensive guide will walk you through everything you need to know about Bun 1.2, from initial installation to advanced usage patterns. Whether you're a beginner looking to explore modern JavaScript tooling or an experienced developer considering a switch from Node.js, this tutorial will provide you with the knowledge and practical steps needed to harness Bun's full potential.

What Makes Bun 1.2 Special

Bun isn't just another JavaScript runtime. Built from the ground up using Zig and powered by the JavaScriptCore engine (the same engine that powers Safari), Bun delivers performance improvements that often surpass Node.js by significant margins. The 1.2 release brings remarkable enhancements that make it more compatible, faster, and more feature-complete than ever before.

The key differentiator lies in Bun's integrated approach. Instead of relying on separate tools for package management (npm), testing (Jest), and bundling (webpack), Bun provides all these capabilities natively. This integration eliminates the overhead of context switching between different tools and reduces the complexity of modern JavaScript development workflows.

Performance benchmarks consistently show Bun outperforming Node.js in various scenarios. For instance, Bun 1.2 can handle three times more requests per second than Node.js when running a simple Express "Hello World" server. These performance gains aren't just theoretical – they translate to faster development cycles, reduced server costs, and improved user experiences in production applications.

Installation and Initial Setup

Getting started with Bun 1.2 is straightforward, with installation options available for all major operating systems. The installation process has been streamlined to ensure developers can get up and running quickly without complex configuration steps.

Installing on macOS and Linux

For Unix-based systems, the recommended installation method uses the official install script. Open your terminal and run the following command:

curl -fsSL https://bun.sh/install | bash

This script automatically detects your system architecture and downloads the appropriate binary. The installer places Bun in your local .bun directory and updates your shell's PATH configuration. After installation completes, restart your terminal or source your shell configuration file to ensure the bun command is available.

Alternatively, macOS users can install Bun through Homebrew, which provides easier version management and integration with other development tools:

brew tap oven-sh/bun
brew install bun

Installing on Windows

Windows users have multiple installation options. The PowerShell method provides the most straightforward approach:

powershell -c "irm bun.sh/install.ps1|iex"

For users who prefer package managers, Scoop offers an alternative installation path:

scoop install bun

Verifying Installation

After installation, verify that Bun is working correctly by checking the version:

bun --version

You should see output indicating Bun 1.2.x or later. If the command isn't recognized, ensure your shell configuration includes the Bun installation directory in your PATH.

Understanding Bun's Core Features

Bun 1.2 introduces several groundbreaking features that set it apart from traditional JavaScript runtimes. These capabilities work together to create a cohesive development environment that prioritizes both performance and developer experience.

Enhanced Node.js Compatibility

One of the most significant improvements in Bun 1.2 is expanded Node.js compatibility. The release includes support for crucial APIs such as fs, net, and HTTP, with new additions including dgram, http2, and cluster modules. This compatibility layer makes migration from Node.js projects much more feasible, as most existing code will run without modifications.

The compatibility extends beyond basic APIs to include better support for CommonJS and ES Modules interoperability. Bun 1.2 handles the complex interactions between these module systems more gracefully, reducing the friction developers often experience when working with mixed codebases.

Native Database Integration

Bun 1.2 introduces built-in PostgreSQL support through Bun SQL, eliminating the need for external database libraries in many scenarios. This native integration provides significant performance advantages over traditional database connectors while maintaining a familiar API structure.

The Bun SQL implementation uses tagged template literals to prevent SQL injection attacks, drawing inspiration from popular libraries like Postgres.js. Here's how you can establish a database connection and execute queries:

import { sql } from 'bun';
 
const db = sql`postgres://username:password@localhost:5432/database`;
 
// Execute queries using tagged templates
const users = await db`
  SELECT id, name, email 
  FROM users 
  WHERE active = ${true}
`;

MySQL support is planned for future releases, expanding Bun's database capabilities even further.

Performance comparison chart showing Bun vs Node.js benchmarks

Package Management Revolution

Bun's package manager represents a fundamental rethinking of how JavaScript dependencies should be handled. The 1.2 release introduces a plain text lockfile format that simplifies code reviews and merge conflict resolution – a common pain point with npm's binary lockfile format.

The package manager is designed to be npm-compatible while delivering superior performance. Installation times are often 10-20x faster than npm, thanks to Bun's efficient caching mechanisms and parallel processing capabilities. The package manager also handles workspace and monorepo scenarios more elegantly, with built-in support for complex dependency relationships.

Creating Your First Bun Project

Now that Bun is installed and configured, let's create a practical project that demonstrates its capabilities. This walkthrough will cover project initialization, dependency management, and basic application development.

Project Initialization

Bun provides a streamlined project initialization process through the bun init command. Navigate to your desired project directory and run:

mkdir my-bun-project
cd my-bun-project
bun init

The initialization wizard will prompt you for project details including name, entry point, and project type. Bun can scaffold both library and server projects, with appropriate configurations for each use case. The generated project structure includes essential files like package.json, tsconfig.json (for TypeScript projects), and a basic entry point file.

Installing Dependencies

Adding dependencies to your Bun project follows familiar patterns while leveraging Bun's superior performance. Install packages using commands similar to npm:

# Install production dependencies
bun add express
bun add react react-dom
 
# Install development dependencies
bun add -d @types/node
bun add -d typescript
 
# Install global packages
bun add -g nodemon

Bun's package installation process includes automatic peer dependency resolution and smart caching mechanisms that significantly reduce installation times for subsequent projects.

Building a Simple Web Server

Let's create a basic Express server to demonstrate Bun's runtime capabilities. Create an index.js file in your project root:

import express from 'express';
 
const app = express();
const port = process.env.PORT || 3000;
 
app.get('/', (req, res) => {
  res.json({ 
    message: 'Hello from Bun 1.2!',
    runtime: 'bun',
    version: process.version
  });
});
 
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

Run your server using:

bun run index.js

The server starts almost instantaneously, showcasing Bun's fast cold start times. Visit http://localhost:3000 to see your application in action.

Advanced Configuration and Optimization

Bun 1.2 offers extensive configuration options that allow developers to fine-tune performance and behavior for specific use cases. Understanding these options can help you maximize the benefits of switching to Bun.

Performance Tuning

Bun includes several built-in optimizations that work automatically, but you can further enhance performance through configuration. The bunfig.toml file in your project root allows you to customize various aspects of Bun's behavior:

# bunfig.toml
[install]
cache = true
registry = "https://registry.npmjs.org"
frozen = false
 
[run]
shell = "bash"
silent = false
 
[build]
minify = true
target = "node"

For HTTP servers, Bun 1.2 includes native WebSocket and HTTP/2 support, eliminating the need for third-party libraries in many scenarios. This native implementation provides better performance and reduced memory overhead compared to userland alternatives.

TypeScript Integration

Bun's TypeScript support is particularly impressive, offering native transpilation without requiring separate build steps. The 1.2 release includes faster TypeScript transpilation speeds and better type definitions for Bun's APIs.

To enable TypeScript in your project, simply use .ts files instead of .js. Bun automatically handles transpilation:

// server.ts
interface User {
  id: number;
  name: string;
  email: string;
}
 
const users: User[] = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
 
export function findUser(id: number): User | undefined {
  return users.find(user => user.id === id);
}

Run TypeScript files directly without compilation:

bun run server.ts

Testing with Bun

Bun includes a built-in test runner that's compatible with Jest APIs while offering superior performance. Create test files using the .test.js or .test.ts extension:

// math.test.ts
import { expect, test } from 'bun:test';
 
test('addition works correctly', () => {
  expect(2 + 2).toBe(4);
});
 
test('async operations', async () => {
  const result = await Promise.resolve(42);
  expect(result).toBe(42);
});

Run tests using:

bun test

The test runner provides detailed output, code coverage reports, and watch mode for continuous testing during development.

Migration Strategies from Node.js

Migrating existing Node.js applications to Bun 1.2 requires careful planning, but the enhanced compatibility makes the process more straightforward than previous versions. Here's a systematic approach to migration.

Assessment and Compatibility Check

Before beginning migration, audit your existing codebase for potential compatibility issues. Bun 1.2 supports most Node.js APIs, but some edge cases might require attention. Pay special attention to:

  • Native modules and binary dependencies
  • File system operations with specific Node.js behaviors
  • Process management and child process spawning
  • Specific npm package versions that rely on Node.js internals

Create a compatibility checklist by running your test suite with Bun to identify any immediate issues:

# In your existing Node.js project
bun test
bun run start

Gradual Migration Approach

Rather than attempting a complete migration immediately, consider a gradual approach that minimizes risk. Start by migrating development and testing workflows while keeping production deployments on Node.js initially.

Begin with new projects or isolated microservices where the impact of any compatibility issues is limited. This approach allows you to gain familiarity with Bun's ecosystem while maintaining stability in critical systems.

For existing projects, create a parallel development environment using Bun:

# Create a new package.json script for Bun
{
  "scripts": {
    "dev": "node server.js",
    "dev:bun": "bun run server.js",
    "test": "jest",
    "test:bun": "bun test"
  }
}

Dependency Management Migration

One of the smoothest aspects of Bun migration is dependency management. Bun can work with existing package.json files and node_modules directories, making the transition seamless:

# Remove existing node_modules and lockfiles
rm -rf node_modules package-lock.json
 
# Install dependencies with Bun
bun install

Bun creates its own lockfile format, but maintains compatibility with npm registries and package specifications. Monitor bundle sizes and installation times to quantify the improvements Bun provides.

Production Deployment Considerations

Deploying Bun applications to production requires understanding how Bun differs from Node.js in containerized and serverless environments. The 1.2 release includes several improvements that make production deployment more reliable.

Docker Integration

Containerizing Bun applications follows similar patterns to Node.js, with some optimizations specific to Bun's architecture. Here's an effective Dockerfile template:

FROM oven/bun:1.2
 
WORKDIR /app
 
# Copy package files
COPY package.json bun.lockb ./
 
# Install dependencies
RUN bun install --frozen-lockfile
 
# Copy application code
COPY . .
 
# Expose port
EXPOSE 3000
 
# Start application
CMD ["bun", "run", "start"]

Bun's smaller runtime footprint often results in smaller container images compared to Node.js equivalents. The native performance improvements also mean you can often use smaller instance sizes for the same workload capacity.

Monitoring and Observability

Production Bun applications benefit from the same monitoring approaches used with Node.js, with some Bun-specific considerations. Health check endpoints, metric collection, and logging work identically, but you may notice different resource utilization patterns due to Bun's performance characteristics.

Consider implementing Bun-specific metrics to track the performance improvements:

import { performance } from 'perf_hooks';
 
// Track request handling times
app.use((req, res, next) => {
  const start = performance.now();
  res.on('finish', () => {
    const duration = performance.now() - start;
    console.log(`${req.method} ${req.path}: ${duration}ms`);
  });
  next();
});

Best Practices and Common Pitfalls

Successful adoption of Bun 1.2 requires understanding both its strengths and limitations. Here are proven best practices and common issues to avoid.

Leverage Bun's Integrated Toolchain

One of Bun's primary advantages is its integrated approach to JavaScript tooling. Instead of maintaining separate configurations for package management, testing, and bundling, consolidate these concerns under Bun's unified interface. This reduces configuration complexity and improves build reproducibility across different environments.

Avoid mixing Bun with other JavaScript toolchains unnecessarily. While Bun can coexist with tools like webpack or Rollup, you'll achieve better performance and simpler maintenance by using Bun's built-in capabilities where possible.

Memory Management Considerations

While Bun generally uses memory more efficiently than Node.js, its garbage collection behavior differs slightly. Monitor memory usage patterns, especially in long-running applications, and consider implementing periodic health checks that can detect memory leaks early.

For applications with high memory requirements, take advantage of Bun's faster startup times to implement restart-based memory management strategies that would be impractical with slower runtimes.

Ecosystem Compatibility

Although Bun 1.2 significantly improves Node.js compatibility, some packages may still exhibit unexpected behavior. Maintain a comprehensive test suite and consider implementing integration tests that verify critical third-party package functionality in your specific use case.

Keep track of packages that provide Bun-specific optimizations or alternatives. The Bun ecosystem is rapidly expanding, and native implementations often provide better performance than Node.js compatibility layers.

Looking Forward: The Future of Bun

Bun 1.2 represents a significant milestone in JavaScript runtime evolution, but it's just the beginning. The development team has outlined an ambitious roadmap that promises even more compelling features in future releases.

Upcoming features include expanded database support with native MySQL integration, enhanced debugging capabilities, and continued performance optimizations. The growing ecosystem around Bun suggests that tooling and framework support will continue expanding rapidly.

For developers considering the adoption of modern development tools, understanding how AI-powered development environments work alongside performant runtimes like Bun can provide additional productivity benefits.

The JavaScript community's reception of Bun has been overwhelmingly positive, with major frameworks and libraries beginning to explicitly support and optimize for Bun's unique capabilities. This trend suggests that early adoption of Bun provides strategic advantages that will compound over time.

Conclusion

Bun 1.2 represents a paradigm shift in JavaScript development, offering a compelling combination of performance, simplicity, and compatibility that addresses long-standing pain points in the ecosystem. The comprehensive feature set, from integrated package management to native database support, creates opportunities for more streamlined development workflows.

The migration path from Node.js, while requiring careful planning, offers substantial benefits in terms of performance, developer experience, and operational simplicity. Teams that invest in learning Bun's capabilities now position themselves to take advantage of continued innovations in the JavaScript runtime space.

As the JavaScript ecosystem continues evolving, tools like Bun 1.2 demonstrate that significant performance improvements and developer experience enhancements remain achievable through thoughtful engineering and community collaboration. Whether you're building new applications or considering migration strategies for existing projects, Bun 1.2 deserves serious consideration as a foundation for modern JavaScript development.

The combination of proven compatibility, exceptional performance, and integrated tooling makes Bun 1.2 not just an interesting alternative to Node.js, but a compelling choice for teams prioritizing development velocity and runtime efficiency. As adoption continues growing and the ecosystem matures, Bun is positioned to play an increasingly important role in shaping the future of JavaScript development.