{"id":13799451,"url":"https://github.com/afenton90/koa-react-router","last_synced_at":"2025-04-14T20:31:25.923Z","repository":{"id":125251096,"uuid":"79468614","full_name":"afenton90/koa-react-router","owner":"afenton90","description":"react-router middleware for koa 2.","archived":false,"fork":false,"pushed_at":"2019-04-29T15:31:23.000Z","size":236,"stargazers_count":38,"open_issues_count":0,"forks_count":3,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-04-10T08:05:02.719Z","etag":null,"topics":["koa","koa2","middleware","react","react-router"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/koa-react-router","language":"JavaScript","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/afenton90.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-01-19T15:49:25.000Z","updated_at":"2023-02-24T17:10:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"b509b2f4-46a1-4a35-ab41-60466798eb2e","html_url":"https://github.com/afenton90/koa-react-router","commit_stats":{"total_commits":43,"total_committers":6,"mean_commits":7.166666666666667,"dds":0.2790697674418605,"last_synced_commit":"5d0924fea707fb1bb97a164de7b5727fcfb6a482"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/afenton90%2Fkoa-react-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/afenton90%2Fkoa-react-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/afenton90%2Fkoa-react-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/afenton90%2Fkoa-react-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/afenton90","download_url":"https://codeload.github.com/afenton90/koa-react-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248955547,"owners_count":21189158,"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":["koa","koa2","middleware","react","react-router"],"created_at":"2024-08-04T00:01:02.855Z","updated_at":"2025-04-14T20:31:24.952Z","avatar_url":"https://github.com/afenton90.png","language":"JavaScript","readme":"# koa-react-router\n\nkoa 2 middleware for React server side rendering and routing with [react-router 5](https://github.com/ReactTraining/react-router).\n\n\u003e Looking for React Router 3 support see [v1](https://github.com/afenton90/koa-react-router/tree/v1.1.2) docs.\nTry React Router 5 though it's awesome!\n\n## Usage\n\nTo install `koa-react-router`:\n\n```\n  npm install koa-react-router react react-dom react-router --save\n```\n\n\u003e Note: `react` `react-dom` \u0026 `react-router` are all `peerDependencies` of `koa-react-router`.\n\n`koa-react-router` can be mounted easily in a koa 2 application like so:\n\n```js\n  // index.js\n  import Koa from 'koa';\n  import reactrouter from 'koa-react-router';\n  import App from './App';\n  import Container from './containers/PageContainer';\n\n  const app = new Koa();\n\n  app.use(reactrouter({\n    App,\n    onError: (ctx, err) =\u003e console.log('I Have failed!!!!'),\n    onRedirect: (ctx, redirect) =\u003e console.log('I have redirected!'),\n    onRender: (ctx) =\u003e ({ Container })\n  }));\n```\n\n## API\n\n`koa-react-router` requires the following parameters:\n\n### `App`\n\nThe `App` config prop should be a react component that contains one or more React Router 4 `Route` components to be rendered.\nFor example:\n```jsx\n  // App.js\n  import React from 'react';\n  import { Route } from 'react-router';\n  import Home from '../containers/Home';\n  import Article from '../containers/Article';\n\n const App = () =\u003e\n    \u003cdiv\u003e\n      \u003ch1\u003eThis is my App!\u003c/h1\u003e\n      \u003cRoute path=\"/\" component={Home} exact /\u003e\n      \u003cRoute path=\"/article\" component={Article} exact /\u003e\n    \u003c/div\u003e;\n\n  // index.js\n  // ...imports\n  import App from './App';\n\n  // ... koa app setup\n  app.use(reactrouter({\n    App,\n    // Other callbacks\n  }));  \n```\n### `preRender`\n\nCallback function called before rendering `App`.\nThis callback can either be a normal function which returns a valid component or it can return a `Promise` which then resolves and returns a valid component.\nThe function accepts the following parameters:\n\n* `component` - The `StaticRouter` wrapped around the `App`.\n\n\u003e This callback could be used to wrap the `component` with any other higher-order component before it gets rendered\n\n### `onError`\n\nCallback function called when an error occurs whilst route matching or rendering.  \nThe function accepts the following parameters:\n\n* `ctx` - The Koa [`Context`](http://koajs.com/#context) object.\n* `err` - The error that was caught when matching routes.\n\n### `onRedirect`\n\nCallback function called if a `Redirect` route is matched.  \nThe function accepts the following parameters:\n\n* `ctx` - The Koa [`Context`](http://koajs.com/#context) object.\n* `redirectUrl` - The url to redirect to.\n\n### `onRender`\n\nCallback function called before sending a response to the client.\nThis function must be supplied, and must return an object that contains the following property:\n\n#### `Container`\nThis should be a React component that wraps around the rendered route.  \nTypically this will be the template for the page, however this is not mandatory.  \nAs such this component is rendered using `renderToStaticMarkup`.  \nThe component must accept the `children` prop and insert it when rendered.\nFor example:  \n\n```jsx\n  // ./containers/Container\n  import React from 'react';\n\n  const Container = (props) =\u003e\n    \u003chtml lang=\"en\"\u003e\n      \u003chead\u003e\n        \u003ctitle\u003eHello Container\u003c/title\u003e\n      \u003c/head\u003e\n      \u003cbody\u003e\n        \u003cdiv id=\"app\"\u003e\n          {props.children}\n        \u003c/div\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e;\n\n  export default Container;\n```\n\nThis would then be supplied to `koa-react-router` via the `onRender` callback like so:\n\n```js\n  // index.js\n  import Koa from 'koa';\n  import reactrouter from 'koa-react-router';\n  import App from './App';\n  import Container from './containers/Container';\n\n  const app = new Koa();\n\n  app.use(reactrouter({\n    App,\n    onRender: (ctx) =\u003e ({ Container })\n  }));\n```\n\nAs well as the `Container` property this callback can optionally return:\n\n#### `containerRenderer`\n\nOptional function for handling the rendering of a container component.  \nThis function has one argument which is `view`. This argument is the currently rendered view of the app.  \nThis function may be used if some custom props need to be injected into the container component, such as an initial Redux state.  \nThis function should be used instead of the `Container` property when returning from `onRender`.  \nFor example you may want to render the container as follows:\n\n```js\n  // index.js\n  import Koa from 'koa';\n  import reactrouter from 'koa-react-router';\n  // ...other imports\n\n  const app = new Koa();\n\n  const state = // Create state.\n\n  app.use(reactrouter({\n    App,\n    onRender: (ctx) =\u003e ({\n      containerRenderer: (view) =\u003e\n      \u003chtml lang=\"en\"\u003e\n        \u003chead\u003e\n          \u003cscript dangerouslySetInnerHTML={{ __html: state}} /\u003e\n        \u003c/head\u003e\n        \u003cbody\u003e\n          \u003cp\u003ehello container\u003c/p\u003e\n          \u003cdiv dangerouslySetInnerHTML={{ __html: view }} /\u003e\n        \u003c/body\u003e\n      \u003c/html\u003e\n    })\n  }));\n```\n\nThe final page render would look something like:\n\n```html\n\u003chtml lang=\"en\"\u003e\n  \u003chead\u003e\n    \u003cscript\u003e//State config\u003c/script\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cp\u003ehello container\u003c/p\u003e\n    \u003cdiv\u003e\n      \u003c!-- View html in here --\u003e\n    \u003c/div\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n### `id`\n\nOptional id for React to use as the base of the app. **Default**: `app`\n\nIn order for React to re-hydrate the DOM on the client it needs to know where it should attach itself. In a previous version of `koa-react-router` this was not [possible](https://github.com/afenton90/koa-react-router/issues/11). This property allows you to add a custom root id to the DOM. For example, if you set this to `root`, the output would look something like.\n\n```html\n\u003chtml lang=\"en\"\u003e\n  \u003chead\u003e\n    \u003cscript\u003e//State config\u003c/script\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cdiv id=\"root\"\u003e\n      \u003c!-- View html in here --\u003e\n    \u003c/div\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\n\n## Router Context\nReact Router 4 added support for a [static router context](https://reacttraining.com/react-router/web/example/static-router) this context can be used in your application, to pass values from your router to other middleware and drive behaviour for routes.  \n`koa-react-router` makes this context available on the koa `ctx` in the following location:  \n```js\nctx.state.routerContext;\n```\n\nOne example of using this context is setting a `status` in the route context so a later middleware can set that as this response code. \nThe common use case of status is already taken care of. So if one of your routes sets a `status` prop whilst rendering that will be set as the response status See [Not found](#what-do-i-do-with-routes-that-are-not-found-) in the FAQ section for an example.  \nUse the `routerContext` for whatever you want in your app, some common recipes will be added to this repo at a later date.\n\n## FAQ\n\nThis release includes some deprecated props. As React Router has come with some major changes so has `koa-react-router`.\n\n### No more routes prop ?\nThe `routes` prop has gone in favour of the `App` config prop. Where you would have passed in your static routes before you can now pass in your `App` component that contains the React Router routes. For example:\n\n```jsx\n// App.js\n  import React from 'react';\n  import { Route } from 'react-router';\n  import Home from '../containers/Home';\n  import Article from '../containers/Article';\n\n  const App = () =\u003e\n    \u003cdiv\u003e\n      \u003ch1\u003eThis is my App!\u003c/h1\u003e\n      \u003cRoute path=\"/\" component={Home} exact /\u003e\n      \u003cRoute path=\"/article\" component={Article} exact /\u003e\n    \u003c/div\u003e;\n```\nReact Router 4 gives you the flexibility to define your routes wherever you want in your app, and so does `koa-react-router`.\n\n### What do I do with routes that are not found ?\nThe previous version of `koa-react-router` supported a `onNotFound` callback. This has been deprecated in favour of defining a `status` prop on the React Router static context and using a `Switch` component in your app. For example, our `App` component may be written as:\n\n```jsx\n  import React from 'react';\n  import { Route, Switch } from 'react-router';\n  import Home from '../containers/Home';\n  import Article from '../containers/Article';\n\n  const NotFound = ({ status }) =\u003e\n    \u003cRoute\n      render={({ staticContext }) =\u003e {\n        if (staticContext) staticContext.status = status;\n        return \u003cdiv\u003eThis route has not been found Soz!\u003c/div\u003e;\n      }}\n    /\u003e;\n\n  const App = () =\u003e\n    \u003cdiv\u003e\n      \u003ch1\u003eThis is my App!\u003c/h1\u003e\n      \u003cSwitch\u003e\n        \u003cRoute path=\"/\" component={Home} exact /\u003e\n        \u003cRoute path=\"/article\" component={Article} exact /\u003e\n        \u003cNotFound status={404} /\u003e\n      \u003c/Switch\u003e\n    \u003c/div\u003e;\n```\n\nIf not other routes are matched the `NotFound` component will be rendered, and `koa-react-router` will set the response code status.\n","funding_links":[],"categories":["仓库"],"sub_categories":["中间件"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fafenton90%2Fkoa-react-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fafenton90%2Fkoa-react-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fafenton90%2Fkoa-react-router/lists"}