Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HTML from Next.js middleware?

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?

like image 726
Ali EXE Avatar asked Nov 24 '25 17:11

Ali EXE


2 Answers

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

like image 162
Jonathan Wieben Avatar answered Nov 26 '25 08:11

Jonathan Wieben


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' } }
    )
}
like image 29
juliomalves Avatar answered Nov 26 '25 06:11

juliomalves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!