We can create server-side rendered React apps and static sites easily Next.js.
In this article, we’ll take a look at route middlewares and preview mode with Next.js.
Connect/Express Middleware Support
We can use Connect compatible middleware.
For example, we can add the cors
middleware by installing it and adding to our Next.js app.
To install it, we run:
npm i cors
or
yarn add cors
Then we can add it to our API route by writing:
import Cors from 'cors'
const cors = Cors({
methods: ['GET', 'HEAD'],
})
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
async function handler(req, res) {
await runMiddleware(req, res, cors)
res.json({ message: 'hello world' })
}
export default handler
We imported the Cors
function.
Then we use it to create the cors
middleware.
We can specify the request methods that can be used with the route.
The runMiddleware
function runs the middleware by calling the fn
middleware function and then resolve to the result
if it’s successful.
Otherwise, the promise is rejected.
The handler
is the route handler that runs the middleware and then returns the response.
Response Helpers
Next.js comes with various response helpers.
The res.status(code)
method lets us set the status code of the response.
code
is an HTTP status code.
res.json(json)
method lets us send a JSON response.
json
is a valid JSON object.
res.send(body)
lets us send an HTTP response, where body
is a string, object, or buffer.
res.redirect
takes an optional status
and path
to let us redirects to a specific path or URL.
The default value of status
is 307.
For example, we can call them by writing:
export default (req, res) => {
res.status(200).json({ name: 'hello' })
}
They can be chained together.
Preview Mode
We can preview routes that are statically generated.
Next.js has a preview mode feature to solve the problem.
It’ll render the pages at request time instead of build time and fetch the draft content instead of the published content.
To use it, we call the res.setPreviewData
method to do the preview.
For example, we can write:
export default (req, res) => {
res.setPreviewData({})
res.end('Preview mode')
}
to enable it.
Securely Accessing Data
We can access data by writing from the preview route and send to our page.
To do this, we create our preview API route by creating the pages/api/preview.js
file:
export default async (req, res) => {
const response = await fetch(`https://yesno.wtf/api`)
const data = await response.json();
res.setPreviewData(data)
res.redirect('/post')
}
We get the data from an API and call setPreviewData
so that we can get it from the getStaticProps
function in our page JavaScript file.
Then we redirect to our file so that we can see the data on our page.
In pages/post.js
, we write:
function Post({ data }) {
return (
<div>{data && data.answer}</div>
)
}
export async function getStaticProps(context) {
if (context.preview) {
return {
props: {
data: context.previewData
}
}
}
return { props: { data: { answer: 'not preview' } } }
}
export default Post
We check is preview mode is on by checking the context.preview
property.
If it’s true
, then we get the preview data from context.previewData
.
And then we display the data
in our Post
component.
Conclusion
We can add preview mode with Next.js so that we can view the output before it goes live.
Also, we can use Connect or Express middleware in our Next.js apps.