Buntal JS Documentation

website·Indexed 31 days ago

https://buntaljs.org/docs

A framework for creating HTTP servers with file-based routing and middleware.

Tokens
1K
Snippets
8
Records
8
Agent score
7%

What's inside Buntal JS

  1. Implement middleware and request validation

    Use the h higher-order function to create handlers with middleware. The first function acts as middleware; if it returns a response (e.g., a 403 error), the request chain stops. Otherwise, it proceeds to the subsequent handler.
    import { h } from '@buntal/http'
    
    export const GET = h(
      (req, res) => {
        console.log('Hi, this is a middleware!')
    
        if (req.query.name !== 'John') {
          return res.status(403).json({
            error: 'Forbidden'
          })
        }
      },
      (req, res) => res.json({
        pong: 1
      })
    )
  2. Create a full-stack page with server-side data fetching

    In Buntal JS, the index.tsx file serves as the route entry point. You can implement server-side data fetching by exporting a $ function, which receives the request and returns data to the page component.
    import type { Req } from '@buntal/http'
    
    // Server-side data fetcher
    export const $ = async (req: Req) => {
      const resp = await fetch(`https://api.example/data/${req.params.id}`)
      return await resp.json() as { name: string }
    }
    
    // Page component
    export default function HomePage({ data, query }: {
      data?: Awaited<ReturnType<typeof $>>,
      query: Record<string, string>
    }) {
      return (
        <div>
          <h1>Hello, {data?.name || query.name || 'Buntal'}!</h1>
        </div>
      )
    }
  3. Define endpoints using file-based routing

    Buntal JS automatically loads files within the configured appDir for routing. For example, a file at ./app/ping.ts can define a GET handler using the h helper function.
    import { h } from '@buntal/http'
    
    export const GET = h(
      (req, res) => res.json({
        pong: 1
      })
    )
  4. Pass type-safe data using Context

    The context object allows passing data between middleware and final handlers. The h function accepts generic types to ensure the context is type-safe.
    type User = {
      id: string
      name: string
    }
    
    export const GET = h<{}, User>(
      (req, res) => {
        if (!req.headers.get('Authorization')) {
          return res.status(401).json({
            error: 'Unauthorized'
          })
        }
    
        req.context = {
          id: '123',
          name: 'John Doe'
        }
      },
      (req, res) => res.json({
        name: req.context?.user.name
      })
    )
  5. Create an HTTP server with file-based routing and middleware

    Initialize an HTTP server using the Http class. By specifying appDir, Buntal JS enables file-based routing. Global middleware (such as CORS and logging) can be applied using app.use(), and endpoints can be defined declaratively.
    import { Http } from '@buntal/http'
    import { cors, logger } from '@buntal/http/middlewares'
    
    // initialize the HTTP server
    const app = new Http({
      port: 4001,
      appDir: './app' // Enable file-based routing!
    })
    
    // add middlewares
    app.use(cors())
    app.use(logger())
    
    // define a simple GET endpoint with a type-safe params
    app.get('/hello/:name', (req, res) => {
      return res.json({
        hello: `Hello ${req.params.name}`
      })
    })
    
    // start the server!
    app.start((server) => {
      console.log(`Server running at http://localhost:${server.port}`)
    })
  6. Define a root layout for the application

    The layout.tsx file defines the HTML shell (head, body, etc.) and wraps all page content via the children prop.
    export default function RootLayout({ children }: Readonly<{
      children: React.ReactNode
    }>) {
      return (
        <html>
          <head>
            <meta charSet="UTF-8" />
            <title>Buntal App</title>
            <meta name="viewport" content="width=device-width, initial-scale=1" />
            <link rel="stylesheet" href="/globals.css" />
          </head>
          <body>{children}</body>
        </html>
      )
    }
  7. Manage HTTP responses (JSON, Text, Status, Headers, Cookies)

    Buntal JS provides a chainable response API to configure the HTTP lifecycle.
    // Send JSON (sets Content-Type: application/json)
    res.json({ data: 'some value' });
    
    // Send Plain Text (sets Content-Type: text/plain)
    res.text('Hello, World!');
    
    // Set Status Code (chainable)
    res.status(400).json({ error: 'Bad Request' });
    
    // Set Custom Headers (chainable)
    res.headers({
      'Cache-Control': 'no-cache',
      'X-Custom-Header': 'MyValue',
    }).json({ message: 'Hello' });
    
    // Set or Delete Cookie
    // To delete, set value to null
    res.cookie('access_token', token, {
      maxAge: 60 * 60 * 2, // 2 hours
      httpOnly: true,
      path: '/'
    });