I have a blog made with Next.js and data is coming from CMS (Headless WordPress).
Assume every post has a title and an id. I want to create short links for my blog, so every site.com/blog/[id] (or site.com/blog/?id=[id]) automatically redirects to site.com/blog/[title].
Also, it should be dynamic; so every time a new post is created, the short link should be generated too.
I'm a little bit confused about how to do this. Should I do it per post? Should I define redirect/rewrites in Next.js config? Should I do it server-side, like with .htaccess? Should it be redirect or rewrite?
Also in GitHub Discussions: https://github.com/vercel/next.js/discussions/39897
You can use Next.js middleware to dynamically redirect the short URLs to their long URLs counterparts.
Unlike
redirectsinnext.config.jsthat are generated at build time, middleware runs on each request allowing for newly created pages to be redirected to.Add the following
middleware.jsfile at the same level as thepagesfolder.The above will redirect URLs like
/b?id=1or/b/1to the appropriate/blog/slug-for-id-1, given thatgetTitleByIdis able to do that mapping.