{"id":16885769,"url":"https://github.com/haikyuu/inertia-node-adapter","last_synced_at":"2025-04-11T12:36:03.625Z","repository":{"id":55090870,"uuid":"328662512","full_name":"haikyuu/inertia-node-adapter","owner":"haikyuu","description":"Inertia adapter for express, koa and frameworks on top. Includes a flash middleware as a bonus","archived":false,"fork":false,"pushed_at":"2021-01-18T14:30:17.000Z","size":244,"stargazers_count":7,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-04T17:39:56.004Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/haikyuu.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-01-11T12:49:54.000Z","updated_at":"2024-11-28T01:51:20.000Z","dependencies_parsed_at":"2022-08-14T11:40:41.532Z","dependency_job_id":null,"html_url":"https://github.com/haikyuu/inertia-node-adapter","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haikyuu%2Finertia-node-adapter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haikyuu%2Finertia-node-adapter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haikyuu%2Finertia-node-adapter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/haikyuu%2Finertia-node-adapter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/haikyuu","download_url":"https://codeload.github.com/haikyuu/inertia-node-adapter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248402349,"owners_count":21097328,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-13T16:36:56.590Z","updated_at":"2025-04-11T12:36:03.601Z","avatar_url":"https://github.com/haikyuu.png","language":"TypeScript","funding_links":[],"categories":["Recently Updated","Adapters"],"sub_categories":["[Nov 29, 2024](/content/2024/11/29/README.md)","Server-side"],"readme":"![example workflow name](https://github.com/haikyuu/inertia-node-adapter/workflows/test-and-build/badge.svg)\n\nNote that while this is working software. It's still in very early experimentation stage.\n\n# inertia-node-adapter\n\nInertia adapter for nodejs - supports Express and Koa.\n\nThis is a fork of https://github.com/jordankaerim/inertia-node with added support for koa, flash messages and integration tests that adhere to Inertia protocol.\n\nThis also includes a flash middleware for koa and express as a bonus. You can use it or use your own.\n\n## Usage\n\nFor working examples, see the `__tests/testServers` folders. It contains two servers in koa and express. Note The code is a bit tangled because it was written for integration tests in mind.\n\n### Koa\n\n```typescript\nimport { inertiaKoaAdapter as inertia, koaFlash } from 'inertia-node-adapter';\nimport session from 'koa-session';\nimport Router from '@koa/router';\n\nconst version = '1';\n\napp.use(session({ maxAge: 86400000 }, app));\napp.use(koaFlash()); // optional, but requires using middleware session beforehand\napp.use(\n  inertia({\n    version,\n    html: getHtml,\n    flashMessages: (ctx) =\u003e ctx.flash.flashAll(), // optional, depends on the flash middleware used\n  })\n);\nconst router = new Router();\n// in your router handlers\nrouter.get('/home', async (ctx, next) =\u003e {\n  // if flash middleware was added.\n  ctx.flash.setFlashMessage('success', 'User created successfully');\n\n  ctx.Inertia.render({\n    component: 'home',\n    props: { name: 1 },\n    url: '/home',\n    version,\n  });\n  next();\n})\n  app.use(router.routes());\n  return next();\n});\n```\n\n### Express usage\n\n```typescript\nimport express from 'express';\nimport session from 'express-session';\n\nconst app = express();\n\napp.use(session({ secret: 'secret' }));\nconst router = express.Router();\n\nrouter.get('/home', async (req, res, next) =\u003e {\n  // if flash middleware was added.\n  req.flash.setFlashMessage('success', 'User created successfully');\n\n  req.Inertia.render({\n    component: 'home',\n    props: { name: 1 },\n    url: '/home',\n    version,\n  });\n});\napp.use(flash());\napp.use(\n  inertia({\n    version,\n    html: getHtml,\n    flashMessages: (req) =\u003e req.flash.flashAll() },\n  })\n);\napp.use(router);\n```\n\n## Usage details\n\n`inertia-node` expects two arguments:\n\n1. `html`: a function that receives the Inertia `page` object and an optional `viewData` object that you can populate with additional data. The function should return an HTML string.\n2. `version` (optional): your current asset version\n\nIt will return a standard Node.js middleware that you can use with Express.js, Polka etc (or koa if you're using koa adapter). Functions can be accessed from the `Inertia` object that will be added to the `request` / `context`. You can chain functions together but you can't call another function after calling [`render`](#renderPage) or [`redirect`](#redirectUrl).\n\n**Note:** In your HTML view function make sure to always stringify the `page` object and include it in the `data-page` attribute of the HTML node you want to render your JavaScript app in. For more infos on how Inertia works read [the protocol](https://inertiajs.com/the-protocol) on the Inertia website.\n\n## API\n\n### setViewData(data)\n\n1. `data`, _Object_ - An Object of additional data you want to pass to your HTML view function\n\n`setViewData` can be used to pass additional data to your [HTML view function](#usage) such as the page's title or other meta data.\n\n```javascript\n.use(({ Inertia }, _, next) =\u003e {\n  Inertia.setViewData({\n    title: \"Todo App\",\n    description:\"A Web App to Create and Manage To-dos\"\n  })\n\n  next();\n})\n\n// ...\n\nconst html = (page, viewData) =\u003e `\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n  \u003chead\u003e\n    \u003cmeta charset=\"utf-8\" /\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width,initial-scale=1\" /\u003e\n\n    \u003cmeta name=\"description\" content=\"${viewData.description}\"\u003e\n    \u003ctitle\u003e${viewData.title}\u003c/title\u003e\n\n    \u003clink rel=\"stylesheet\" href=\"/build/bundle.css\" /\u003e\n    \u003cscript defer type=\"module\" src=\"/build/main.js\"\u003e\u003c/script\u003e\n  \u003c/head\u003e\n\n  \u003cbody id=\"app\" data-page='${JSON.stringify(page)}'\u003e\u003c/body\u003e\n\u003c/html\u003e\n`;\n```\n\n### shareProps(props)\n\n1. `props`, _Object_ - An object of props you want to include with every `render` call\n\nShared props are props that will be combined with the props you pass to the [`render`](#renderPage) function. When you call `shareProps` more than once, props shared from previous calls will be merged with props from any subsequent calls.\n\n```javascript\n.use(({ Inertia }, _, next) =\u003e {\n  Inertia.shareProps({ username: \"ironMan\" })\n  next();\n})\n.get(\"/todo\", ({ Inertia }) =\u003e {\n  Inertia.render({\n    component: \"Todo\",\n    props: {\n      todo: [\n        { text: \"Study Korean\", done: false },\n        { text: \"Cook Arabic food\", done: false },\n      ]\n    }\n    // JavaScript component on the client will receive\n    // {\n    //   username: \"ironMan\",\n    //   todo: [\n    //     { \"Study Korean\", done: false },\n    //     { \"Cook Arabic food\", done: false },\n    //   ]\n    // }\n  });\n})\n```\n\n### setHeaders(headers)\n\n1. `headers`, _Object_ - An Object of custom headers you want to include in your response\n\nAdd custom headers to your response.\n\n**Note:** Headers that are required by Inertia take precedence and cannot be overwritten.\n\n```javascript\n.get(\"/\", ({ Inertia }) =\u003e {\n  Inertia\n    .setHeaders({\n      token: \"7pTgHCv0JgeAyyBRDpUi\"\n    })\n    .render({\n      component: \"Index\",\n      props: { username: \"ironMan\" }\n    });\n})\n```\n\n### setStatusCode(statusCode)\n\n1. `statusCode`, _number_ - The response's status code\n\nChange the status code when sending a response. Useful for e.g. when you want to render an error. Headers set from previous calls will be merged with headers set from any subsequent calls.\n\n```javascript\n.get(\"/\", ({ Inertia }) =\u003e {\n  Inertia.render({\n    component: \"Index\",\n    props: { username: \"ironMan\" }\n  });\n})\n.use(({ Inertia }) =\u003e {\n  Inertia\n    .setStatusCode(404)\n    .render({\n      component: \"Error\",\n      props: { message: \"Page not found\" },\n    });\n})\n```\n\n### render(page)\n\n1. `page`, _Object_ - the Inertia page object\n\nThis function will send your response as either a HTML or JSON string to the client depending on wether the client is requesting your page for the first time or is making a subsequent Inertia request.\n\nThe Inertia page object consists of the following properties:\n\n1. `component`, _string_ - The name of the JavaScript component to render on the client\n2. `props`, _Object_ - The page props (data)\n3. `url`, _string_ - The URL of the route. This will be automatically added by the middleware.\n4. `version`, _string_ - The asset version. This will be automatically added by the middleware.\n\n```javascript\n.get(\"/todo\", ({ Inertia }) =\u003e {\n  Inertia.render({\n    component: \"Todo\",\n    props: {\n      todo: [\n        { text: \"Study Korean\", done: false },\n        { text: \"Cook Arabic food\", done: false },\n      ]\n    },\n  });\n})\n```\n\nOn Partial Reloads only props requested by the client will be sent. To improve performance on the server you can wrap each prop inside a function so that they will only be evaluated when necessary.\n\n```javascript\n.get(\"/todo\", ({ Inertia }) =\u003e {\n  const todoArray = async () =\u003e await database.getTodo();\n  const bookmarks = async () =\u003e await database.getBookmarks();\n\n  Inertia.render({\n    component: \"Todo\",\n    props: {\n      todoArray,\n      bookmarks\n    },\n  });\n})\n```\n\nNow when the client only requests `todoArray` the middleware will hit the database only once and not call `bookmarks`.\n\n### redirect(url)\n\n1. `url`, _string_ - The URL to redirect to\n\nRedirect the client to a different URL.\n\n```javascript\n.post(\"/todo\", (req, res) =\u003e {\n  database.createTodo(req.body);\n  req.Inertia.redirect(\"/todo\");\n})\n```\n\n**Note:** Inertia requires you to use a `303` status code when redirecting upon a `PUT`, `PATCH` or `DELETE` request and a `302` status code otherwise. The `redirect` function will automatically take care of this for you. If you handle redirects yourself make sure to select the correct status code.\n\n**Note:** Calling [`setStatusCode`](#renderPage) before [`redirect`](#redirectUrl) has no effect.\n\n## Credits\n\n- [Jordan Kaerim](https://github.com/jordankaerim).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhaikyuu%2Finertia-node-adapter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhaikyuu%2Finertia-node-adapter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhaikyuu%2Finertia-node-adapter/lists"}