Skip to content

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

License

Notifications You must be signed in to change notification settings

platypusrex/next-merge-props

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

65 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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