šÆWhat is Bun ?
Bun is a JavaScript runtime.It is an attemptāto overcome the limitations of Node. js back-end development setup with a separateāfront-end using React, Vue, or Angular.
Unlike Node. js, Bun does notādepend on npm and doesn't need any other dependencies to function. Instead, it features a built-in standard library containing support for various protocols and modules, such as environment variables, HTTP,āwebsocket, file system, etc.
š ļø PreparingāYour Environment
āļøStep 1: Install Bun
If you have not installedāBun yet then you can do it by running the following command in your terminal:
powershell -c "irm bun.sh/install.ps1 | iex"
āļøStep 2: Create a New Project
Create a new folder for your project.
mkdir BarterX
cd BarterX
āļøstep 3: Intialize your project
Run the following command to initialize your Bun project:
bun init
This command will set up the neccessary files for your project.
āļø Creating API Endpoints :
Now the enviroment has been set up letās create simple API endpoint.
now open vs code and create index.
Bun.serve({
fetch(req) {
const url = new URL(req.url);
// Create a simple GET endpoint
if (url.pathname === "/api/hello" && req.method === "GET") {
return new Response(JSON.stringify({ message: "Hello, Bun!" }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
// Return 404 for other routes
return new Response("Not Found", { status: 404 });
},
});
// Log server information
console.log("Server is running at http://localhost:3000");
š§ Explanation of the Code
Port Customization:
Use
process.argv
to get the port number from the command line.Defaults to
3000
if no port is specified.
The
serve
Function:Tells Bun to create an HTTP server.
Handles incoming requests using the
fetch
function.
Request Handling:
Checks if the URL matches
/api/hello
with aGET
request.Sends back a greeting if matched.
Returns a 404 error for other routes.
š„ļø Running Your API
To run your API, execute the following command in your terminal:
bun run index
Test it by visiting http://localhost:3000/api/hello
in your browser.
{
"message": "Hello, Bun!"
}
If no port is specified, the server defaults to port 3000.
šWhy Use Bun for APIs?
Blazing Performance:
- Built for speed with Zig and an optimized runtime design.
Simplicity:
- Native HTTP server removes the need for additional libraries like Express.
All-in-One Tool:
- Combines a runtime, bundler, and package manager to streamline development.
šÆConclusion
Bun makes creating lightweight, high-performance APIs a breeze. From native routing to JSON parsing, Bun simplifies modern web development. Whether youāre building a simple app or a production-ready system, Bunās features make it a top choice.