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-router-guards

v2.0.6

Published

next-router-guards

Downloads

154

Readme

next-router-guards NPM Module

A library for secure routes in your web project.

The security depend on next middleware, so it improve performance.

Comparison

Why use the next-router-guards is better than alternatives?

  1. Performance. It's executing faster than use useEffect inside of page, because checking for access to the page occurs on the server side.
  2. Data safety. When we use useEffect (or other ways to protect pages based on client side conditions) user can see private data in network, and also user can see the private page before he will be relocated to another page.
  3. All page access settings will be in one place.

Example of using next-router-guards. next-router-guards

Example of using useEffect. useEffect

Requirements

This package has the following peer dependencies:

Install

npm i next-router-guards

Usage

Here is a very basic example of how to use Next Router Guards.

Example of pages:

pages.png

Manually

  1. Create routes and RoutesParams for show which params you need to pass for go to the page. Example:
// /config/routes.g.ts

export type RoutesParams = {
  index: null,
  private: null,
  public: null,
  userId: {id: number},
};

export const routes: {readonly [key in keyof RoutesParams]: string} = {
  index: '/',
  private: '/private',
  public: '/public',
  userId: '/user/[id]',
};
  1. Create routes config with existing guard (You can see examples of guards in /examples). Example:
// /config/routes.config.ts

import {AuthorizedGuard} from 'next-router-guards';

import {routes, type RoutesParams} from './routes.g';

export const routesConfig = new AuthorizedGuard<RoutesParams>({
  routes,
  config: {
    routes: {
      index: {isPublic: true},
      public: {isPublic: true},
      private: {isPublic: false},
      userId: {isPublic: false},
    },
    defaultPublicRoute: routes.public,
    defaultPrivateRoute: routes.private,
    checkAuthorized: (request) => request.cookies.has('token'),
  },
});
  1. BE SURE to write this code in the root of your project in middleware.ts.
// /middleware.ts

import type {NextRequest} from 'next/server';

import {routesConfig} from './config/routes.config';

export async function middleware(request: NextRequest) {
  return routesConfig.accessRequest(request);
}

CLI

  1. Install next-router-guards global
npm i next-router-guards -g
  1. Run CLI for create initial config or for update routes and routes config depend on your files in pages folder.
nrg

nrg.png 3) Pass types into the routesParams and routesConfig values.

Custom guard.

In both variants of using (manual or CLI) you can use your own guard with a custom logic. If you want to create your guard:

  1. Create new class extends from Guard with 3 generic params: (TRoutesParams - name of pages with their params, TConfigProps - config of your router. TGuardRoute - config of your routes).
  2. Override canAccessRoute method to provide your logic.
  3. You can also override canAccessDefaultRoute if you need it.
  4. Make instance from your class with filled config. Example:
// /core/services/active.guard.service.ts

import {Guard} from 'next-router-guards';
import type {CanAccessRouteParams, RouteUrl} from 'next-router-guards';
import {NextRequest} from 'next/server';

type ActiveGuardRoute = {
  isActive?: boolean | ((request: NextRequest) => boolean) | ((request: NextRequest) => Promise<boolean>);
};

type ActiveGuardConfigProps = {
  defaultPage: RouteUrl;
};

export class ActiveGuard<TRoutesParams extends RoutesParams> extends Guard<
  TRoutesParams,
  ActiveGuardConfigProps,
  ActiveGuardRoute
> {
  protected async canAccessRoute(
    params: CanAccessRouteParams<TRoutesParams, ActiveGuardConfigProps, ActiveGuardRoute>,
  ): Promise<string | null> {
    const isActive: boolean = params.route.config.isActive
      ? typeof params.route.config.isActive === 'boolean'
        ? params.route.config.isActive
        : await params.route.config.isActive(params.request)
      : true;

    return isActive ? null : params.config.defaultPage;
  }
}

Additional features

useRouterGuards

You can use useRouterGuards hook for push or replace pages. What a difference between push pages with useRouter (from next) and useRouterGuards (from next-router-guards)?

  1. When you pushing (or replacing) pages with useRouterGuards you can choose the pages from list of variants (if you're using typescript your IDE will pass you variants of pages based on TRoutesParams) useRouterGuardsIDE.png
  2. You must fill params of your pushing page with the correct type. useRouterGuardsUncorrectedParam.png

How to use:

  1. Wrap your content (in _app) in RouterGuardsProvider and pass your routes const
import type {AppProps} from 'next/app'
import {RouterGuardsProvider} from "next-router-guards";

import {routes} from "@/config/routes.g";

export default function App({Component, pageProps}: AppProps) {
  return (
    <RouterGuardsProvider routes={routes}>
      <Component {...pageProps} />
    </RouterGuardsProvider>
  )
}
  1. Use useRouterGuards inside of your pages and pass RoutesParams generic for better IDE helping.
const {routes} = useRouterGuards<RoutesParams>();

Combine guards

In some cases you may want to combine guards for setting access to request. For example, it can be usefully for secure pages and api. In this case you can pass urlRegexp in any guard config. Create some guards with config. And call combineGuards in widdleware.ts. Example:

import type {NextRequest} from 'next/server';
import {combineGuards} from "next-router-guards";

import {routesConfig} from './config/routes.config';
import {apiConfig} from './config/api.config';

export async function middleware(request: NextRequest) {
  return combineGuards([routesConfig, apiConfig]);
}

Troubleshooting

  • name routes with /* (e.g. not found page) with _ in start of route name. Because of all routes starts comparing with current page by alphabet.
  • when you have error: "Can't resolve 'fs'", just add config.resolve.fallback = {fs: false} in your your next.config.js for webpack configuration.
module.exports = {
  webpack(config) {
    config.resolve.fallback = {
      fs: false,
    };

    return config;
  },
}

License

next-router-guards is released under the MIT license.