Skip to content

Bun

The Bun JavaScript runtime can run a web standard HTTP server with Cloud Auth like this.

Verifier

An authenticateRequest function that validates an incoming web standard request can be implemented in src/authenticate.ts like this:

ts
import { createVerifier } from '@featherscloud/auth'

const appId = '<your-app-id>'
const verifier = createVerifier({ appId })

/**
 * Verify authentication for a web standard request object.
 * Will throw an error if verification was not successful.
 * 
 * @param request The request object
 * @returns The authentication information like `user` and `token`
 */
export async function authenticateRequest(request: Request) {
  const header = request.headers.get('Authorization')

  return verifier.verifyHeader(header!)
}

Server

Then the BunJS server can then use it in a src/index.ts like this:

ts
import { authenticateRequest } from "./authenticate.ts"

// Headers for handling CORS
const headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Headers': '*',
  'Access-Control-Allow-Methods': 'GET',
  'Access-Control-Allow-Origin': '*',
}

const server = Bun.serve({
  port: 3030,
  async fetch(request) {
    // Get the path from the request object
    const url = new URL(request.url);
    const path = url.pathname;

    try {
      // Handle CORS preflight request
      if (request.method === 'OPTIONS') {
        return new Response(null, {
          status: 200,
          headers,
        })
      } else if (path === '/message') {
        // Verify the Authorization header and get the user information
        const { user } = await authenticateRequest(request)
  
        if (!user) {
          throw new Error('Cloud auth user not found')
        }
  
        const body = {
          message: `Hello ${user.email} from BunJS!`,
        }
  
        return Response.json(body, {
          status: 200,
          headers,
        })
      } else {
        throw new Error(`Not found ${path}`)
      }
    }
    catch (error) {
      return Response.json({ error: (error as any).message }, {
        status: 400,
        headers,
      })
    }
  },
})

console.log(`BunJS application listening on http://localhost:${server.port}`)

The full Bun example server can be found here.