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-merge-props

v1.1.1

Published

Compose and merge the resulting props object from Next.js getServerSideProps/getStaticProps

Downloads

13,802

Readme

next-merge-props

npm Package Downloads License Coverage Status CI

Overview

Prior to Next.js introducing getServerSideProps and getStaticProps, wrapping page components using HOC's was a popular pattern that allowed you to easily grab things from SSR like cookies or session data using getInitialProps and reuse in any page. The goal of the lib is simply to aid in recreating a similar pattern, allowing you to compose any number of specialized data fetching functions and merge the results of each.

Installation

npm

npm install --save next-merge-props

or yarn

yarn add next-merge-props

Usage

mergeProps(...fns) | mergeProps([fns], options)

Parameters can be expressed in 2 ways.

...fns: ...(GetServerSideProps | GetStaticProps)[]`

or

fns: (GetServerSideProps | GetStaticProps)[]
options?: {
  resolutionType: 'parallel' | 'sequential',
  shortCircuit: 'redirect-and-notfound' | 'redirect-only' | 'notfound-only' | 'never',
  debug: boolean
}

default options: {
  resolutionType: 'sequential',
  shortCircuit: 'redirect-and-notfound',
  debug: false
}

Options:

resolutionType The resolutionType option allows you to specify how mergeProps resolves the promise returned from each data function. The default is sequential and will resolve each promise in order (left to right). If set to parallel, the results of each function are wrapped in Promise.all and resolved in parallel.

shortCircuit The shortciruit option allows you to configure the behavior of server side function execution. Specifically when the output of the function is either a redirect object or notFound flag as officially supported in both getServerSideProps and getStaticProps. This aforementioned behavior is to simply exit and return if the payload of any executed function includes either of the values above. This is turned on by default for both redirect and notfound.

Note: This can only be configured if your using the sequential resolution type, which happens to be the default resolution type. The short-circuit can be configured in several ways.

  1. redirect-and-notfound
  2. redirect-only
  3. notfound-only
  4. never

debug The debug option will log any intersections that occur during the merge. The default is false and it will be disabled in production.

import { mergeProps} from 'next-merge-props';

const getServerSideProps = mergeProps(
  getServerSideFooProps,
  getServerSideBarProps,
);

// or with options parameter
const getServerSideProps = mergeProps([
  getServerSideFooProps,
  getServerSideBarProps,
], {
  resolutionType: 'parallel',
  shortCircuit: 'never',
  debug: true,
});

Example

note: example below utilizes getServerSideProps but can be swapped with getStaticProps
// getServerSideFooProps.ts

import { GetServerSidePropsContext } from 'next';

export interface GetServerSideFooProps {
  foo: 'foo';
}

interface GetServerSideFooPropsOptions {
  onSuccess: (ctx: GetServerSidePropsContext) => void;
}

export const getServerSideFooProps = ({ onSuccess }: GetServerSideFooPropsOptions) =>
  async (ctx: GetServerSidePropsContext) => {
    onSuccess && onSuccess(ctx);
    return {
      props: {
        foo: 'foo',
      }
    };
  };
// getServerSideUserProps.ts

import { User } from '../interfaces';

export interface GetServerSideUserProps {
  users: User[];
}

interface GetServerSideUserPropsOptions {
  onSuccess: (users: User[]) => void;
}

export const getServerSideUserProps = ({ onSuccess }: GetServerSideUserPropsOptions) =>
  async () => {
    const res = await fetch(`http://localhost:3000/api/users`);
    const users = await res.json();

    if (users && onSuccess) {
      onSuccess(users)
    }

    return {
      props: {
        users,
      }
    };
  };

Usage without options:

// pages/index.tsx

import { NextPage } from 'next';
import { mergeProps } from 'next-merge-props';
import { getServerSideFooProps, GetServerSideFooProps } from '../lib/getServerSideFooProps';
import { getServerSideUserProps, GetServerSideUserProps } from '../lib/getServerSideUserProps';

type IndexPageProps =
  GetServerSideFooProps &
  GetServerSideUserProps;

const IndexPage: NextPage<IndexPageProps> = (props) => (
  <div>
    <pre>{JSON.stringify(props, null, 2) }</pre>
  </div>
);

export const getServerSideProps = mergeProps<IndexPageProps>(
  getServerSideFooProps({
    onSuccess: (ctx) => {
      // ...do something with context here
    }
  }),
  getServerSideUserProps({
    onSuccess: (users) => {
      // ...do something with the result here
    }
  })
);

export default IndexPage;

Usage with options:

// pages/index.tsx

import { NextPage } from 'next';
import { mergeProps } from 'next-merge-props';
import { getServerSideFooProps, GetServerSideFooProps } from '../lib/getServerSideFooProps';
import { getServerSideUserProps, GetServerSideUserProps } from '../lib/getServerSideUserProps';

type IndexPageProps =
  GetServerSideFooProps &
  GetServerSideUserProps;

const IndexPage: NextPage<IndexPageProps> = (props) => (
  <div>
    <pre>{JSON.stringify(props, null, 2) }</pre>
  </div>
);

export const getServerSideProps = mergeProps<IndexPageProps>([
  getServerSideFooProps({
    onSuccess: (ctx) => {
      // ...do something with context here
    }
  }),
  getServerSideUserProps({
    onSuccess: (users) => {
      // ...do something with the result here
    }
  })
], {
  resolutionType: 'parallel',
  debug: true,
});

export default IndexPage;

The resulting prop object:

{
  foo: 'foo',
  users: [
    { id: 101, name: 'Alice' },
    { id: 102, name: 'Bob' },
    { id: 103, name: 'Caroline' },
    { id: 104, name: 'Dave' },
  ]
}

Contributors

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT