1.0.9 • Published 6 years ago
next-page-middleware v1.0.9
Next Page Middleware
NextJS painless page middleware.
// pages/index.js
import React from 'react'
import Head from 'next/head'
import GetMetaInfo from '../middlewares/GetMetaInfo'
const Home = props => (
<div>
<Head>
<title>{props.title}</title>
</Head>
<div className="hero">
<h1 className="title">Welcome to Next.js!</h1>
<p className="description">{props.description}</p>
</div>
</div>
)
Home.middlewares = [GetMetaInfo]
export default Home
// middlewares/GetMetaInfo.js
export default _appContext => {
return {
title: 'Home in Middleware',
description: 'Next Page Middleware'
}
}
Install
With Npm
npm i next-page-middleware --save
With Yarn
yarn add next-page-middleware
Activate On App
You can activate next-page-app in your application by adding a few line to the _app.js
module.
What is _app.js
import React from 'react'
import { NextAppWithMiddleware } from 'next-page-middleware'
class MyApp extends NextAppWithMiddleware {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
Use On Your Page
You can add middlewares
in your page just like the getInitialProps
property.
import React from 'react'
import GetMetaInfo from '../middlewares/GetMetaInfo'
const Home = props => (
<div>
<div className="hero">
<h1 className="title">{props.title}</h1>
<p className="description">{props.description}</p>
</div>
</div>
)
Home.middlewares = [GetMetaInfo]
export default Home
Define A Middleware
You can use your middlewares synchronously or asynchronously. AppContext will be sent to each middleware. Ignore the order of middleware list you added because middlewares is called with Promise.all.
// Synchronous Middleware
export default ({ ctx: { req: { url } } }) => {
return {
title: 'Home in Middleware',
cannonical: url,
description: 'Next Page Middleware'
}
}
// Asynchronous Middleware
export default async () => {
const todos = await fetch(
'https://jsonplaceholder.typicode.com/todos/1'
).then(response => response.json())
return {
todos
}
}
License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details