Example : I need to redirect this URL : https://example.com/data/publications to this one : https://example.com/data/publications.json
I already tried Next.js redirection but I failed to add a string that is not starting with /
Example, this doesn't work :
async redirects() {
return [
{
source: '/data/:slug',
destination: '/data/:slug.json',
permanent: true,
},
]
},
Adding () around .json doesn't help
How about using a middleware? Middleware is a function that executes when client connects to a specific route.
To use middleware; inside your "pages/data" folder, create "_middleware.js" file and use the code below. This code checks if the url has "json" extension end of it. If it doesn't, then it redirects the client to the url with "json" version.
import { NextResponse } from 'next/server';
export default function myMiddleware(req, e) {
if (!req.url.endsWith("json")) return new NextResponse.redirect(`${req.url}.json`);
}