@uxf/router

UXF Router

Usage no npm install needed!

<script type="module">
  import uxfRouter from 'https://cdn.skypack.dev/@uxf/router';
</script>

README

@uxf/router

How to use

Install:

yarn add @uxf/router

Create routes.ts inside your project:

import { Router as UxfRouter } from "@uxf/router";

export interface RouteList {
    index: null;
    "blog": null;
    "blog-article": { articleId: string };
}

const router = new UxfRouter<RouteList>({
    index: "/",
    "blog": "/blog",
    "blog-article": "/blog/:articleId",
});

export const Link = router.getLink();
export const useRouter = router.getUseRouter();
export const Router = router.getSingletonRouter();
export const getRequestHandler = router.getRequestHandler;
export type RouteName = keyof RouteList;

On the server

import next from "next";
import { getRequestHandler } from "./routes";
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handler = getRequestHandler(app);

const { createServer } = require("http");
app.prepare().then(() => {
    createServer(handler).listen(3000);
});

Custom request handler

import next from "next";
import { RequestHandler } from "@uxf/router";
import { getRequestHandler } from "./routes";

const app = next();

const customHandler: RequestHandler = async (req, res, pathname, queryParams) => {
    const html = await app.renderToHTML(req, res, pathname, queryParams);
    
    res.send(html);
}

const handler = getRequestHandler(app, customHandler);

On the client

// pages/index.js
import { Link } from '../routes'

export default () => (
    <Link route='blog-article' params={{ articleId: 12 }}>
      <a>Hello world</a>
    </Link>
)

Anchor

// pages/index.js
import { Link, Router } from '../routes'

export default () => (
    <Link route='blog-article' anchor="...">
      <a>Hello world</a>
    </Link>
)

// or

Router.push('blog-article', null, { anchor: "..." });