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-with-error

v1.2.0

Published

Next.js HoC to render the Error page and send the correct HTTP status code from any page

Downloads

325

Readme

next-with-error

Build Status Dependencies

Next.js plugin to render the Error page and send the correct HTTP status code from any page's getInitialProps.

This higher-order-components allows you to easily return Next.js's Error page + the correct HTTP status code just by defining error.statusCode in your pages getInitialProps:

// pages/something.js

const SomePage = () => (
  <h1>I will only render if error.statusCode is lesser than 400</h1>
);

SomePage.getInitialProps = async () => {
  const isAuthenticated = await getUser();

  if (!isAuthenticated) {
    return {
      error: {
        statusCode: 401
      }
    };
  }

  return {
    // ...
  };
};

Contents:

Installation

npm install next-with-error

Usage

withError([ErrorPage])(App)

Adapt pages/_app.js so it looks similar to what is described in the official Next.js documentation and add the withError HoC.

// _app.jsx
import withError from 'next-with-error';

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default withError()(MyApp);

Then, in any of your pages, define error.statusCode if needed in your page's getInitialProps

// pages/article.js
import React from 'react';
import fetchPost from '../util/fetch-post';

class ArticlePage extends React.Component {
  static async getInitialProps() {
    const article = await fetchPost();

    if (!article) {
      // No article found, let's display a "not found" page
      // Will return a 404 status code + display the Error page
      return {
        error: {
          statusCode: 404
        }
      };
    }

    // Otherwise, all good
    return {
      article
    };
  }

  render() {
    return (
      <h1>{this.props.article.title}</h1>
      // ...
    );
  }
}

export default HomePage;

generatePageError(statusCode[, additionalProps])

If you find the code to write the error object is a bit verbose, feel free to use the generatePageError helper:

import { generatePageError } from 'next-with-error';

// ...

SomePage.getInitialProps = async () => {
  const isAuthenticated = await getUser();

  if (!isAuthenticated) {
    return generatePageError(401);
  }

  return {};
};

You can use the additionalProps argument to pass custom props to the Error component.

Custom error page

By default, withError will display the default Next.js error page. If you need to display your own error page, you will need to pass it as the first parameter of your HoC:

import Error from './_error';
// ...

export default withError(ErrorPage)(MyApp);

Work to automate this is tracked here.

The error object properties are accessible via the props of your custom Error component (props.statusCode, props.message, etc if you have custom props).

⚠️ If your custom Error page has a getInitialProps method, the error object will be merged in getInitialProps's return value. Be careful to not have conflicting names.

Custom props

You can also pass custom props to your Error Page component by adding anything you would like in the error object:

// /pages/article.js
const HomePage = () => <h1>Hello there!</h1>;

HomePage.getInitialProps = () => {
  return {
    error: {
      statusCode: 401,
      message: 'oopsie'
    }
  };
};

export default HomePage;
// /pages/_error.js

import React from 'react';

const Error = (props) => {
  return (
    <>
      <h1>Custom error page: {props.error.statusCode}</h1>
      <p>{props.error.message}</p>
    </>
  );
};

export default Error;

⚠️ Be careful to add default values for your custom props in the Error component, as Next.js routing may bypass next-with-error's behavior by showing the 404 page without the message variable (in this example).

Automatic Static Optimization

You have opted-out of Automatic Static Optimization due to getInitialProps in pages/_app

This plugin, like most Higher-order-Component relying on extending the _app file, will opt-you-out of the Automatic Static Optimization of Next.js. This is a known trade-off to avoid declaring this HoC on each one of your pages.

Things will probably change once Next.js support for plugins will ship.