Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save marcelloinfoweb/dfb19e30a74234cc104839fc8494d05b to your computer and use it in GitHub Desktop.

Select an option

Save marcelloinfoweb/dfb19e30a74234cc104839fc8494d05b to your computer and use it in GitHub Desktop.

Regras para Usar APIs Nativas do Bun em Projetos Next.js + TypeScript

1. Execução e Instalação

  • Sempre rodar scripts com: bun run --bun next dev / bun run --bun next build / bun run --bun next start
  • Usar bun install para instalação de dependências — evitar npm/yarn/pnpm
  • Instalar tipos nativos Bun para TypeScript: bun add -d bun-types

2. Configuração TSConfig

{
  "compilerOptions": {
    "types": ["bun-types"],
    "typeRoots": ["./node_modules/@types", "./node_modules/bun-types"],
    "verbatimModuleSyntax": true
  },
  "include": ["bun-types.d.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

3. API de Arquivos

  • Substituir fs/promises por Bun.file() e Bun.write() para leitura e escrita:
const file = Bun.file('./data.json'); 
const data = await file.json();
await Bun.write('./output.json', JSON.stringify(data));

4. Servidor HTTP Customizado

  • Usar Bun.serve() para servidores auxiliares, com alta performance e zero dependências:
Bun.serve({
  port: 8080,
  fetch(request) {
    return new Response("Bun HTTP Server");
  }
});

5. Utilitários Nativos

  • Hashing seguro com Bun.password.hash() (argon2)
  • Temporizadores precisos com Bun.sleep(ms)
  • Variáveis de ambiente via Bun.env
  • Compressão rápida com Bun.gzipSync() e Bun.deflateSync()
  • Medição de tempo super precisa com Bun.nanoseconds()

6. Testes

  • Executar testes com bun test usando:
import { test, expect } from "bun:test";
test("example", () => {
  expect(true).toBe(true);
});
  • Mais rápido, paralelo e sem dependências extras

7. Scripts recomendados no package.json

{
  "scripts": {
    "dev": "bun run --bun next dev",
    "build": "bun run --bun next build",
    "start": "bun run --bun next start",
    "test": "bun test",
    "type-check": "bun tsc --noEmit",
    "install": "bun install"
  }
}

8. Detectar Runtime Bun

const isBun = !!process.versions.bun;
console.log(`Running on ${isBun ? 'Bun ⚡' : 'Node.js'}`);

9. Regra para Cursor AI (para projetos Next.js/TS)

  • Priorizar Bun APIs (Bun.file(), Bun.serve(), Bun.password.hash() etc) sobre Node.js nativas
  • Sempre executar com bun run --bun
  • Configurar tsconfig com tipos Bun nativos
  • Usar bun para instalação, build e testes
  • Fallback para Node somente se Bun não disponível

Exemplo de uso em API Route Next.js:

export async function GET() {
  const users = await Bun.file('./data/users.json').json();
  const hash = await Bun.password.hash('secret', 'argon2id');
  return Response.json({ users, hash, runtime: process.versions.bun ? 'Bun' : 'Node' });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment