{"id":17655,"library":"fortune-http","title":"Fortune HTTP","description":"Fortune HTTP (`fortune-http`) provides the HTTP implementation for Fortune.js, a non-native graph database abstraction layer for Node.js and web browsers. Currently at version 1.2.28, this module is essential for exposing Fortune.js APIs over HTTP, including default serializers for JSON, HTML, form-encoded data, and form data. It acts as the networking layer, converting internal Fortune.js requests and responses into HTTP interactions. It is explicitly stated as being required for other HTTP serializers within the Fortune.js ecosystem. While a specific release cadence isn't defined, it typically evolves alongside the main Fortune.js project. Its key differentiator is its tight integration with Fortune.js, offering a structured, ad hoc JSON over HTTP API and an HTML interface, contrasting with other network protocols like WebSocket also supported by Fortune.js.","status":"active","version":"1.2.28","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/fortunejs/fortune-http","tags":["javascript","http","fortune"],"install":[{"cmd":"npm install fortune-http","lang":"bash","label":"npm"},{"cmd":"yarn add fortune-http","lang":"bash","label":"yarn"},{"cmd":"pnpm add fortune-http","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This module provides the HTTP interface for a Fortune.js instance, making it a peer dependency.","package":"fortune","optional":false},{"reason":"Runtime dependency for CRC32 calculations, introduced in version 1.2.28.","package":"@node-rs/crc32","optional":false}],"imports":[{"note":"The library is primarily designed for CommonJS environments and uses `require()` for its main export, which is a function. ESM `import` is not officially supported or documented.","wrong":"import fortuneHTTP from 'fortune-http'","symbol":"fortuneHTTP","correct":"const fortuneHTTP = require('fortune-http')"},{"note":"The `fortuneHTTP` export is a function that returns another listener function, not a constructor.","wrong":"const listener = new fortuneHTTP(fortuneInstance, options)","symbol":"listener","correct":"const listener = fortuneHTTP(fortuneInstance, options)"},{"note":"The listener returns a Promise and requires explicit error handling via `.catch()`.","wrong":"server.on('request', listener)","symbol":"requestHandler","correct":"server.on('request', (request, response) => listener(request, response).catch(console.error))"}],"quickstart":{"code":"const http = require('http');\nconst fortuneHTTP = require('fortune-http');\n// A mock Fortune.js instance for demonstration purposes.\n// In a real application, you would initialize Fortune.js.\nconst mockFortuneInstance = {\n  request: async (type, payload) => {\n    console.log(`Fortune.js request: ${type}`, payload);\n    // Simulate database operations\n    if (type === 'create') return { records: [{ id: Math.random().toString(36).substring(7), ...payload.records[0] }] };\n    if (type === 'find') return { records: [{ id: 'abc', message: 'Hello from Fortune!' }] };\n    return { records: [] };\n  }\n};\n\n// Pass in a Fortune instance and an optional options object.\nconst listener = fortuneHTTP(mockFortuneInstance, {\n  // Example customization for HTML serializer (default prefix is empty string)\n  prefix: '/api'\n});\n\nconst server = http.createServer((request, response) =>\n  listener(request, response)\n    .catch(error => {\n      console.error('Fortune HTTP Error:', error.stack);\n      if (!response.headersSent) {\n        response.writeHead(500, { 'Content-Type': 'application/json' });\n        response.end(JSON.stringify({ error: error.message }));\n      }\n    })\n);\n\nconst PORT = process.env.PORT || 3000;\nserver.listen(PORT, () => {\n  console.log(`Fortune HTTP server listening on http://localhost:${PORT}`);\n  console.log(`Try: curl http://localhost:${PORT}/api/find/posts`);\n  console.log(`Try: curl -X POST -H \"Content-Type: application/json\" -d '{\"records\": [{\"message\": \"New post!\"}]}' http://localhost:${PORT}/api/create/posts`);\n});","lang":"javascript","description":"Demonstrates setting up a basic Node.js HTTP server using `fortune-http` with a mock `Fortune.js` instance, showcasing how to handle requests and catch potential errors."},"warnings":[{"fix":"Ensure all calls to the listener function are followed by a `.catch(error => { /* handle error */ })` block.","message":"The `fortuneHTTP` function returns a Promise. All calls to the listener must explicitly handle promise rejections (e.g., with `.catch()`) to prevent unhandled promise errors from crashing the Node.js process.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Position `app.use(listener)` or similar at the end of your middleware chain for routes handled by Fortune HTTP.","message":"When used with middleware frameworks like Express, the `fortune-http` listener should typically be the last middleware in the stack for a given route, as it ends the response by default. Placing other middleware after it may lead to 'Headers already sent' errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that form submissions include appropriate CSRF cookie values prefixed with `CSRF_`.","message":"Form serializers in `fortune-http` require all payloads to include cookie values prefixed with `CSRF_` for Cross-Site Request Forgery (CSRF) protection. Omitting these will result in failed form submissions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If HTTP method overriding is required for form submissions, include `__method__` field in the payload with the desired Fortune.js-accepted method.","message":"The special field `__method__` can be used within form payloads to override the HTTP method. This is a specific mechanism for scenarios where standard HTTP methods cannot be used directly.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For Fortune.js v5.0.0 and later, use `require('fortune-http')` directly instead of `fortune.net.http`.","message":"Previous versions of Fortune.js (before 5.0.0) had HTTP capabilities directly within the core `fortune.net.http` namespace. `fortune-http` was extracted as a separate module in Fortune.js v5.0.0. Older applications may need to update their import paths.","severity":"deprecated","affected_versions":"<5.0.0 (Fortune.js)"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Use CommonJS `const fortuneHTTP = require('fortune-http')` as the primary method of importing.","cause":"Attempting to import `fortune-http` using an ESM `import` statement or incorrectly assuming it's a class, or if CommonJS `require` yields an unexpected value.","error":"TypeError: fortuneHTTP is not a function"},{"fix":"Always append a `.catch()` block to the `listener` call, e.g., `listener(request, response).catch(console.error)`.","cause":"The `listener` function returned by `fortuneHTTP` is asynchronous and returns a Promise. If this Promise rejects and the rejection is not caught, Node.js will log this warning or crash the process in newer versions.","error":"UnhandledPromiseRejectionWarning: Unhandled promise rejection."},{"fix":"Ensure that the `fortune-http` listener is positioned as the last middleware in the chain for the routes it is intended to handle, as it typically ends the response by default.","cause":"When using `fortune-http` within an Express.js or similar middleware stack, another middleware might be attempting to send a response after `fortune-http` has already done so, or vice-versa, due to incorrect ordering.","error":"Error: Headers already sent"},{"fix":"Pass an initialized instance of `Fortune.js` to `fortuneHTTP`, like `fortuneHTTP(myFortuneInstance, options)`.","cause":"The `fortuneHTTP` function was called without providing a valid Fortune.js instance as its first argument.","error":"Fortune HTTP Error: A Fortune instance is required."},{"fix":"Include a cookie value prefixed with `CSRF_` in your form submissions as required by the `fortune-http` form serializers for CSRF protection.","cause":"A request, particularly a form submission, was made to `fortune-http`'s form serializers without the required `CSRF_` prefixed cookie values.","error":"CSRF token mismatch"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}