@scacap/next-app-builder
v0.0.1
Published
Middleware pipeline to create next.js App.
Downloads
7
Readme
next-app-builder
Custom App builder for Next.js.
What is a Custom App
?
Next.js uses the App component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like:
- Persisting layout between page changes
- Keeping state when navigating pages
- Custom error handling using componentDidCatch
- Inject additional data into pages
- Add global CSS
For more details, see offical documentation.
Why a builder?
Generates a custom next App using middleware.
Before:
class CustomNextApp extends App {
static async getInitialProps({ Component, ctx, router }) {
const initialPageProps = await (Component.getInitialProps ? Component.getInitialProps : {});
const data = await fetch(getDataForPage(router.pathname));
return {
pageProps: {
...initialPageProps,
data
}
};
}
render() {
const { Component, pageProps } = this.props;
return (
<SsrDataProvider data={pageProps.ssrData}>
<LayoutComponent>
<Component {...pageProps} />
</LayoutComponent>
</SsrDataProvider>
);
}
}
After:
const ssrDataMiddleware = {
Component: SsrDataProvider,
getInitialProps: ({ router }) => {
const data = await fetch(getDataForPage(router.pathname));
return { data };
}
};
const layoutMiddleware = { Component: LayoutComponent };
nextAppBuilder({
middleware: [ssrDataMiddleware, layoutMiddleware]
});
Installation
Install using Yarn:
yarn add @scacap/next-app-builder
or NPM:
npm install @scacap/next-app-builder --save
Usage
// pages/_app.js
import nextAppBuilder from '@scacap/next-app-builder';
import materialUiMiddleware from '../middlewares/material-ui';
import theme from '../theme';
export default nextAppBuilder({
middleware: [materialUiMiddleware(theme)]
});
API
nextAppBuilder
Creates a custom app that should be the default export of pages/_app.js
.
const CustomApp = appBuilder({
middleware: [
// middlewares here
]
});
middleware
An object containing the following fields:
- name: a human readable identifier of middleware. Optional.
- getInitialProps: a function which is executed before rendering. Used for blocking data requirements for every single page in your application, e.g. server side data fetching. Optional.
- Component: the React component which is rendered in custom App. It's a wrapper component that will receive each page as children. Typically used for adding providers in the App level, e.g. css theme provider. Optional.
- componentDidCatch: invoked when a descendant component throws an error. See more details in the React docs. Optional.
Caveats
Internally, you will be adding a custom getInitialProps in your App. This will disable Automatic Static Optimization in pages without Static Generation.
For more details, see offical documentation.
Contributing
Let's build together our v1! Pull-requests and issue reports are welcome.