I'm trying to return HTTP Status Code 410 (gone) alongside a custom simple HTML:
<h1>Error 410</h1>
<h2>Permanently deleted or Gone</h2>
<p>This page is not found and is gone from this server forever</p>
Is it possible? Because I can't find a method on NextResponse object.
How can I return HTML from middleware?
This is not supported anymore.
Middleware can no longer produce a response body as of v12.2+.
https://nextjs.org/docs/messages/returning-response-body-in-middleware
While it's true that returning a response body from middleware has been disabled from version v12.2, Next.js v13 reintroduced the ability to produce a response as an experimental feature through the allowMiddlewareResponseBody flag in next.config.js.
// next.config.js
module.exports = {
experimental: {
allowMiddlewareResponseBody: true
}
}
After enabling this experimental flag, you can return a response from your middleware as follows.
import { NextResponse } from 'next/server'
export function middleware(request) {
return new NextResponse(
`
<h1>Error 410</h1>
<h2>Permanently deleted or Gone</h2>
<p>This page is not found and is gone from this server forever</p>
`,
{ status: 410, headers: { 'content-type': 'text/html' } }
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With