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-fortress

v5.0.1

Published

This is a Next.js plugin that blocks, redirects, or displays a dummy page for accesses that are not authenticated.

Downloads

196

Readme

codecov npm version

:japanese_castle: next-fortress

This package is a Next.js plugin that provides server-side access control for users when they are in a non-authenticated state.

IPs, Firebase, Amazon Cognito and Auth0 are used to determine authentication, and when a user is in a non-authenticated state, it is possible to redirect or rewrite.

This plugin uses Next.js v12 middleware to control access with edge functions, which makes it faster and reduces client-side code.

Example

next-fortress example

Require

  • Using Next.js >=12

This plugin depends on the middleware of Next.js v12. If you are using Next.js v11 or earlier, please use next-fortress v2.

Installation

npm install --save next-fortress

Usage

All functions define their own fallback and use it as an argument. fallback is a control command in the unauthenticated state to select rewrite, redirect, and the middleware function.

type Fallback = Middleware | {
    type: 'rewrite';
    destination: string;
} | {
    type: 'redirect';
    destination: string;
    statusCode?: 301 | 302 | 303 | 307 | 308;
};

type Middleware = (request: NextRequest, event?: NextFetchEvent) => Response | undefined;

Control by IP address

example

// middleware.ts
import { makeIPInspector } from 'next-fortress/ip'

/*
  type IPs = string | Array<string>
  type makeIPInspector = (allowedIPs: IPs, fallback: Fallback) => Middleware
  // IP can be specified in CIDR format. You can also specify multiple IPs in an array.
*/
export const middleware = makeIPInspector('123.123.123.123/32', {
  type: 'redirect',
  destination: '/'
})

export const config = {
  matcher: ['/admin/:path*'],
}

Control by Firebase

example

// middleware.ts
import { makeFirebaseInspector } from 'next-fortress/firebase'

/*
  type makeFirebaseInspector = (
    fallback: Fallback,
    customHandler?: (payload: any) => boolean
  ) => AsyncMiddleware
*/
export const middleware = makeFirebaseInspector(
  { type: 'redirect', destination: '/signin' }
)

export const config = {
  matcher: ['/mypage/:path*'],
}

Put the Firebase user token into the cookie using the following example.

// cient side code (for example /pages/_app.tsx)
import { FIREBASE_COOKIE_KEY } from 'next-fortress/constants'

firebase.auth().onAuthStateChanged(function (user) {
  if (user) {
    // User is signed in.
    user
      .getIdToken()
      .then((token) => document.cookie = `${FIREBASE_COOKIE_KEY}=${token}; path=/`)
  } else {
    // User is signed out.
    document.cookie = `${FIREBASE_COOKIE_KEY}=; path=/; expires=${
      new Date('1999-12-31T23:59:59Z').toUTCString()
    }`
  }
})

For the second argument of makeFirebaseInspector, you can pass a payload inspection function. This is useful, for example, if you want to ignore some authentication providers, or if you need to ensure that the email has been verified.
If this function returns false, it will enter the fallback case.

// middleware.ts
import { makeFirebaseInspector } from 'next-fortress/firebase'

// Redirect for anonymous users.
export const middleware = makeFirebaseInspector(
  { type: 'redirect', destination: '/signin' },
  (payload) => payload.firebase.sign_in_provider !== 'anonymous'
)

export const config = {
  matcher: ['/mypage/:path*'],
}

NOTE

  • If you want to specify the cookie key, use the environment variable FORTRESS_FIREBASE_COOKIE_KEY.
  • If you use session cookies to share authentication data with the server side, set the environment variable FORTRESS_FIREBASE_MODE to session.

Control by Amazon Cognito

example

// middleware.ts
import { makeCognitoInspector } from 'next-fortress/cognito'

/*
  type UserPoolParams = {
    region: string;
    userPoolId: string;
    userPoolWebClientId: string;
  }

  type makeCognitoInspector = (
    fallback: Fallback,
    params: UserPoolParams,
    customHandler?: (payload: any) => boolean
  ) => AsyncMiddleware
*/
export const middleware = makeCognitoInspector(
  { type: 'redirect', destination: '/signin' },
  {
    region: process.env.COGNITO_REGION,
    userPoolId: process.env.COGNITO_USER_POOL_ID,
    userPoolWebClientId: process.env.COGNITO_USER_POOL_WEB_CLIENT_ID,
  }
)

export const config = {
  matcher: ['/mypage/:path*'],
}

Add ssr: true option to Amplify.configure to handle the Cognito cookies on the edge.

// cient side code (for example /pages/_app.tsx)
import Amplify from 'aws-amplify'

Amplify.configure({
  aws_cognito_identity_pool_id: process.env.NEXT_PUBLIC_COGNITO_IDENTITY_POOL_ID,
  // ...omitted
  ssr: true // this line 
})

For the 3rd argument of makeCognitoInspector, you can pass a payload inspection function. This is useful, for example, if you want to ignore some authentication providers, or if you need to ensure that the email has been verified.
If this function returns false, it will enter the fallback case.

// middleware.ts
import { makeCognitoInspector } from 'next-fortress/cognito'

// Fallback if the email address is not verified.
export const middleware = makeCognitoInspector(
  { type: 'redirect', destination: '/signin' },
  {
    region: process.env.COGNITO_REGION,
    userPoolId: process.env.COGNITO_USER_POOL_ID,
    userPoolWebClientId: process.env.COGNITO_USER_POOL_WEB_CLIENT_ID,
  },
  (payload) => payload.email_verified
)

export const config = {
  matcher: ['/mypage/:path*'],
}

Control by Auth0

example

// middleware.ts
import { makeAuth0Inspector } from 'next-fortress/auth0'

/*
  type makeAuth0Inspector = (
    fallback: Fallback,
    apiEndpoint: string,
    customHandler?: (payload: any) => boolean
  ) => AsyncMiddleware;
*/
export const middleware = makeAuth0Inspector(
  { type: 'redirect', destination: '/singin' },
  '/api/auth/me' // api endpoint for auth0 profile
)

export const config = {
  matcher: ['/mypage/:path*'],
}

To use Auth0, the api root must have an endpoint. @auth0/nextjs-auth0

// /pages/api/auth/[auth0].ts
import { handleAuth } from '@auth0/nextjs-auth0'

export default handleAuth()

For the third argument of makeAuth0Inspector, you can pass a payload inspection function. This is useful, for example, if you need to ensure that the email has been verified.
If this function returns false, it will enter the fallback case.

// middleware.ts
import { makeAuth0Inspector } from 'next-fortress/auth0'

// Fallback if the email address is not verified.
export const middleware = makeAuth0Inspector(
  { type: 'redirect', destination: '/singin' },
  '/api/auth/me',
  (payload) => payload.email_verified
)

export const config = {
  matcher: ['/mypage/:path*'],
}

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

License

This project is licensed under the MIT License - see the LICENSE file for details