koa-nextjs

9.0.0 • Public • Published

koa-nextjs

The main goal of this project is to allow developers to write user interfaces using React and serve them with server-side rendering (SSR) and then re-hydrate it in the browser.

Also enables hot-module replacement (HMR) because it uses Next.js under the scenes. It's possible to have full control over the Next.js settings.

Installation

Install this module and its peer-dependencies with:

yarn add koa-nextjs koa koa-router next react react-dom

Usage

Server-side

// index.js
 
const path = require('path');
const Koa = require("koa");
const RenderEngine = require("koa-nextjs");
 
async function main() {
  const app = new Koa();
 
  const engine = await RenderEngine.start({
    // See: https://nextjs.org/docs#custom-server-and-routing
    options: {
      dev: process.env.NODE_ENV !== "production",
      quiet: true,
      // `pages` directory should be inside /client
      dir: path.join(__dirname, "client"),
      conf: {
        distDir: "build", // relative to `options.dir`
        useFileSystemPublicRoutes: false,
      },
    },
  });
 
  // engine.router is an instance of `koa-router`
  app.use(engine.router.routes());
  // See: https://github.com/koajs/koa/blob/master/docs/api/index.md#appcontext
  app.context.render = engine.renderer();
 
  app.use(async ctx => {
    // Remember to always `await`
    await ctx.render({
      page: "main/Home", // path for a React component in `/client/pages/main/Home.js`
      props: {
        // only plain (serializable) JS primitives or objects.
        user: { name: "" },
      },
      options: {
        // custom Next.js options
      },
    })
  })
}
 
main().catch(err => {
  console.error(err);
  process.exit(1);
});

Client-side

// client/pages/main/Home.js
 
import React from "react";
import { withSSR } from "koa-nextjs/react"; // <-- don't forget this
 
const Home = ({ name, ...props }) => (
  <div {...props}>
    <h1>Hello</h1>
    <p>
      Name: <span>{name}</span>
    </p>
    <p>
      <a href="/about">Go to about</a>
    </p>
  </div>
);
 
export default withSSR()(Home); // <-- don't forget this

Example

See /example for a complete example with styled-components.

Gotchas

  • Hot reloading will not work for server-side files. Use nodemon and make sure to only watch server files.

  • Do not use import Link from "next/link" neither any pre-fetching option. Stick with old-school anchor navigation: <a href="/other-route" />

License

MIT

Dependencies (0)

    Dev Dependencies (9)

    Package Sidebar

    Install

    npm i koa-nextjs

    Weekly Downloads

    2

    Version

    9.0.0

    License

    MIT

    Unpacked Size

    7.31 kB

    Total Files

    6

    Last publish

    Collaborators

    • lopezjurip