{"id":16362,"library":"fortune-json-api","title":"Fortune JSON API Serializer","description":"This package functions as a robust JSON API serializer specifically designed for Fortune.js. It meticulously implements all features outlined in the JSON API specification (jsonapi.org) and adheres closely to its recommendations. The current stable version is 2.3.1. While there isn't a fixed release schedule, updates are typically driven by dependency upgrades, bug fixes, and occasional feature additions, as observed in recent minor bumps. Its core differentiators include deep integration with the Fortune.js data abstraction layer, ensuring consistent and compliant JSON API data formatting, and extensive configurability through an `options` object. This allows developers to fine-tune aspects like URL prefixes, field and type inflection, pagination limits, and buffer encoding, making it an effective tool for building hypermedia-driven APIs on top of Fortune.js without manual serialization overhead.","status":"active","version":"2.3.1","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/fortunejs/fortune-json-api","tags":["javascript","json","api","fortune","http","hypermedia","rest","serializer"],"install":[{"cmd":"npm install fortune-json-api","lang":"bash","label":"npm"},{"cmd":"yarn add fortune-json-api","lang":"bash","label":"yarn"},{"cmd":"pnpm add fortune-json-api","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as the core data layer and ORM replacement that this serializer integrates with.","package":"fortune"},{"reason":"Required to handle the HTTP layer and integrate the serializer into the request/response cycle.","package":"fortune-http"}],"imports":[{"note":"The primary export is the default serializer function. This package is primarily CommonJS-first, so direct ESM `import` might require Node.js's ESM compatibility layers or bundler configuration. The `require` syntax is shown in all documentation examples.","wrong":"const jsonApiSerializer = require('fortune-json-api')","symbol":"jsonApiSerializer","correct":"import jsonApiSerializer from 'fortune-json-api'"},{"note":"This is the idiomatic CommonJS import shown in the official documentation and examples. The serializer is a default export.","symbol":"jsonApiSerializer","correct":"const jsonApiSerializer = require('fortune-json-api')"}],"quickstart":{"code":"const http = require('http');\nconst fortune = require('fortune');\nconst fortuneHTTP = require('fortune-http');\nconst jsonApiSerializer = require('fortune-json-api');\n\n// Define your Fortune.js record types\nconst store = fortune({\n  user: {\n    email: String,\n    name: String,\n    posts: [Array('post'), 'author']\n  },\n  post: {\n    title: String,\n    content: String,\n    author: ['user', 'posts']\n  }\n});\n\nconst listener = fortuneHTTP(store, {\n  serializers: [\n    // The `options` object here is optional.\n    [ jsonApiSerializer, { prefix: '/api', jsonSpaces: 2 } ]\n  ]\n});\n\nconst server = http.createServer((request, response) =>\n  listener(request, response)\n    .catch(error => {\n      console.error('API Error:', error);\n      response.writeHead(500, { 'Content-Type': 'application/vnd.api+json' });\n      response.end(JSON.stringify({ errors: [{ status: '500', title: 'Internal Server Error', detail: error.message }] }));\n    })\n);\n\nconst port = process.env.PORT ?? 8080;\nserver.listen(port, () => console.log(`JSON:API server listening on http://localhost:${port}/api`));\n\n// Example: How to interact (e.g., in another file or via curl)\n/*\ncurl -X POST -H \"Content-Type: application/vnd.api+json\" -d '{\n  \"data\": {\n    \"type\": \"users\",\n    \"attributes\": {\n      \"email\": \"test@example.com\",\n      \"name\": \"Test User\"\n    }\n  }\n}' http://localhost:8080/api/users\n\ncurl http://localhost:8080/api/users\n*/\n","lang":"javascript","description":"This example sets up a basic Fortune.js server with the JSON API serializer, creating an HTTP listener that serves a 'users' and 'posts' resource type over a `/api` prefix."},"warnings":[{"fix":"Ensure `fortune-json-api` is installed (`npm install fortune-json-api`) and explicitly imported via `require('fortune-json-api')` or `import jsonApiSerializer from 'fortune-json-api'`.","message":"Prior to Fortune.js v1.0.0-rc.13, the JSON API serializer was bundled directly within the `fortune` package. This changed to an external module, `fortune-json-api`, requiring explicit installation and import for any projects migrating from very old `fortune` versions (pre-1.0.0-rc.13) to newer ones.","severity":"breaking","affected_versions":"<1.0.0-rc.13 of fortune, all versions of fortune-json-api"},{"fix":"Ensure that `fortune` and `fortune-http` packages are installed with versions compatible with `fortune-json-api` as specified in its `package.json` peer dependencies.","message":"This library is tightly coupled with `fortune` and `fortune-http`. Mismatched major versions of these peer dependencies can lead to unexpected behavior or runtime errors. Always check the `fortune-json-api`'s `package.json` for compatible peer dependency ranges.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully configure the `prefix` option to match your desired API routing strategy. If you need to handle multiple API versions or non-prefixed routes, ensure your `fortune-http` setup correctly dispatches to the right serializer/listener.","message":"The `prefix` option, if set to a path starting with `/`, will rewrite URLs relative to that prefix. For example, a prefix of `/api` will make requests for `/api/users/1` map to the `users` resource with ID `1`. Misunderstanding this behavior can lead to incorrect routing or URL generation.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For CommonJS projects, use `const jsonApiSerializer = require('fortune-json-api')`. For ESM projects, if you encounter import issues, consider using `import jsonApiSerializer from 'fortune-json-api'` and ensuring your build system or Node.js runtime correctly handles CJS default exports.","message":"This package is primarily designed for CommonJS (`require`) environments, and all official examples use this syntax. While it might work with ESM via bundlers or Node.js's compatibility layers, explicit ESM support (e.g., named exports, `.mjs` files) is not documented, which can lead to import errors in pure ESM projects.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change `const jsonApiSerializer = require('fortune-json-api')` to `import jsonApiSerializer from 'fortune-json-api'`. Ensure your Node.js version supports ESM or configure a bundler like Webpack/Rollup if targeting older environments.","cause":"Attempting to use `require()` in an ES Module environment (e.g., in a `.mjs` file or when `\"type\": \"module\"` is set in `package.json`) without a transpilation step.","error":"ReferenceError: require is not defined"},{"fix":"Try `import * as jsonApiModule from 'fortune-json-api'; const jsonApiSerializer = jsonApiModule.default;` or simplify to `import jsonApiSerializer from 'fortune-json-api'` if your environment supports it. Often, setting `esModuleInterop: true` in `tsconfig.json` for TypeScript projects can also resolve this.","cause":"Incorrectly importing a CommonJS default export in an ES Module context, often due to a mismatch in how transpilers or Node.js handle default exports from CJS modules.","error":"TypeError: (0 , fortune_json_api_1.default) is not a function"},{"fix":"Verify that your client-side requests adhere strictly to the JSON API specification, especially regarding the `data`, `type`, `id`, `attributes`, and `relationships` keys in the request body. Common mistakes include wrong `Content-Type` header (should be `application/vnd.api+json`) or missing `data` wrapper.","cause":"The incoming HTTP request body does not conform to the JSON API specification's structure or content rules, leading to validation failure by the serializer.","error":"Error: Invalid JSON API payload"},{"fix":"Install the missing packages: `npm install fortune fortune-http`.","cause":"The required peer dependencies `fortune` or `fortune-http` are not installed or are not resolvable in the current project's `node_modules`.","error":"Cannot find module 'fortune' or Cannot find module 'fortune-http'"}],"ecosystem":"npm"}