npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

next-typed-routes

v1.0.2

Published

Type safe route utilities for Next.js.

Downloads

259

Readme

// /routes.ts
import { createRoute } from "next-typed-routes";

export const routes = {
  // For `/pages/index.tsx`
  top: createRoute("/"),

  // For `/pages/users/index.tsx`
  users: createRoute("/users"),
  // For `/pages/users/[userId].tsx`
  usersDetail: (userId: number) => createRoute("/users/[userId]", { userId }),
};
// /pages/index.tsx
import Link from "next/link";
import { routes } from "../routes.ts";

const targetUserId = 5;

const Page () => (
  <Link {...routes.usersDetail(targetUserId)}>
    <a>Go to the user page (id: {targetUserId})</a>
  </Link>
);

...
Page.getInitialProps = async ({ res }) => {
  // Redirect to `/users/123&limit=30` .
  // This works fine on client-side and server-side.
  movePage(routes.usersDetail(123), { res, queryParameters: { limit: 30 } })
};

Table of Contents

Features

| FEATURES | WHAT YOU CAN DO | |------------------------------------|----------------------------------------------------------| | ❤️ Designed for Next.js | You can use Next.js routing system without custom server | | 🌐 Build for Universal | Ready for Universal JavaScript | | 📄 Write once, Manage one file | All you need is write routes to one file | | 🎩 Type Safe | You can use with TypeScript |

Motivation

Next.js 9 is the first version to support dynamic routing without any middleware. It is so useful and easy to use, and it supports dynamic parameters such as /users/123 .

However the dynamic parameters do not support to be referred type safely. So when we rename a dynamic parameter, we should search codes which use the parameter in <Link> component and others and replace them with a new parameter name. Also it is thought that developers may forget to specify required dynamic parameters when creating links.

next-typed-routes provides some APIs to resolve this issues. You can manage all routes with dynamic parameters in one file and you can create links type safely.

Quick Start

Requirements

  • npm or Yarn
  • Node.js 10.0.0 or higher
  • Next.js 9.0.0 or higher

Installation

$ npm install next-typed-routes

If you are using Yarn, use the following command.

$ yarn add --dev next-typed-routes

Usage

Routes

import { createRoute } from "next-typed-routes";

export const routes = {
  // For `/pages/index.tsx`
  top: createRoute("/"),

  // For `/pages/users/index.tsx`
  users: createRoute("/users"),
  // For `/pages/users/[userId].tsx`
  usersDetail: (userId: number) => createRoute("/users/[userId]", { userId }),
};

Firstly, you need to define routes using next-typed-routes.

createRoute function exported from next-typed-routes returns an object for <Link> component props, which has href and as properties. So when you manage values created by createRoute, you can get <Link> component props via the keys like the following.

<Link {...routes.top}>
  <a>Go to top.</a>
</Link>

// Or
<Link href={routes.top.href} as={routes.top.as}>
  <a>Go to top.</a>
</Link>

Arguments of createRoute

Currently, createRoute accepts three parameters.

<Link {...createRoute("/")} />
<Link {...createRoute("/users", undefined, { limit: 10 })} />
<Link {...createRoute("/users/[userId]/items/[itemId]", { userId: 1, itemId: 2 })} />
  • path: string
    • Required.
    • A page of Next.js. This is a path of files in /pages in general.
  • parameters: { [key: string]: number | string | undefined | null }
    • Optional, default is {} .
    • You can give dynamic parameters as object.
  • queryParameters: { [key: string]: number | string | boolean | null | undefined }
    • Optional, default is {} .
    • You can give query string as object.

Key names

import { createRoute } from "next-typed-routes";

export const routes = {
  // For `/pages/index.tsx`
  "/": createRoute("/"),

  // For `/pages/users/index.tsx`
  "/users": createRoute("/users"),
  // For `/pages/users/[userId].tsx`
  "/users/[userId]": (userId: number) => createRoute("/users/[userId]", { userId }),
};

You can freely name keys of routes , but I recommend you to adopt the same with page file path for key names in order to reduce the thinking time to name them.

Page Mover

import Router from "next/router";
import { createPageMover } from "next-typed-routes";

const movePage = createPageMover("https://you-project.example.com", Router);

movePage("/about");
movePage(createRoute("/"));

next-typed-routes provides a function to reidrect to a specific page using createRoute . This works fine on cliet-side (web browsers) and server-side.

If you want to support server-side, you must give res object from getInitialProps arguments.

Component.getInitialProps = async ({ res }) => {
  movePage("/about", { res });
};

API

createRoute(path, parameters, queryParameters): { href: string, as: string }

createRoute("/")
createRoute("/users", undefined, { limit: 10 })
createRoute("/users/[userId]/items/[itemId]", { userId: 1, itemId: 2 })

Returns an object for <Link> component props.

  • path: string
    • Required
    • A page of Next.js. This is a path of files in /pages in general
  • parameters: { [key: string]: number | string | undefined | null }
    • Optional, default is {}
    • You can give dynamic parameters as object
  • queryParameters: { [key: string]: number | string | boolean | undefined | null }
    • Optional, default is {}
    • You can give query string as object

createPageMover(baseURI, Router): PageMover

createPageMover("https://you-project.example.com", Router);
createPageMover(new URL("https://you-project.example.com"), Router);

Returns a function to redirect URL.

  • baseURI: string | URL
    • Required
    • Your project base URI
  • Router: NextRouter
    • Required
    • Give Router object from next/router in your project

movePage(path, options): void

movePage("/about");
movePage(createRoute("/about"));

movePage("/about", { res, statusCode: 301 });
movePage("/about", { res, queryParameters: { limit: 30 } });

This function is created from createPageMover .

  • path: string | { href: string, as: string }
    • Required
    • A destination path
    • It is possible to give a return value from createRoute
  • options: Options
    • Optional, default is {}
    • res: ServerResponse
      • Required if you want to support server-side redirect
      • A sever response object for server-side
      • It is possible to get a context object which contains this from Next.js getInitialProps arguments
    • queryParameters: { [key: string]: number | string | boolean | undefined | null }
      • An object for query string
      • If path already has query string, it will be merged with queryParameters
    • statusCode: 301 | 302
      • A status code for server-side

Contributing to next-typed-routes

Bug reports and pull requests are welcome on GitHub at https://github.com/jagaapple/next-typed-routes. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

Please read Contributing Guidelines before development and contributing.

License

The library is available as open source under the terms of the MIT License.

Copyright 2019 Jaga Apple. All rights reserved.