Next.js Discord

Discord Forum

Handling redirects without deployments

Unanswered
Silver Fox posted this in #help-forum
Open in Discord
Silver FoxOP
We are using next.js (self-hosted) over a CMS that allows users to create redirects.

We want to avoid performance hits, every time someone adds a redirect. We want to especially avoid rebuilding our nextjs app.

One approach is for us to fetch a list of these redirects in next.js middleware, and then trigger a redirect based on the list. However, this will mean an additional API request with every page request.

We have attempted this approach, but with a way to send a POST req to break the cache, below:

var redirects: any;

const getRedirects = async () => {
  // e.g. { /about-us': {'destination': '/about', 'isPermanent': true}, ... }
  return await (await fetch("http://localhost:3000/api/redirects")).json()
}

export default async function middleware(req: NextRequest) {
    const url = req.nextUrl

    if (!redirects) {
        redirects = await getRedirects()
    }
    else if (req.method == "POST" && url.pathname == process.env.REDIRECT_PATH) {
        if (req.headers.get("x-secret") != process.env.REDIRECT_SECRET) {
            return NextResponse.json({
                message: "Unauthorized"
            }, {
                status: 401
            })
        }

        redirects = await getRedirects()

        return NextResponse.json({
            message: "Accepted"
        }, {
            status: 202
        })
    }


    const redirect = redirects[url.pathname]
    if (redirect) {
        if (redirect.destination.startsWith('http')) {
            return NextResponse.redirect(new URL(redirect.destination));
        }

        return NextResponse.redirect(new URL(redirect.destination, req.url));
    }
}


This cobbled together solution handles this, however, this is not ideal. Is there a better architecture here that we are missing?

0 Replies