How to create short links in Next.js?

814 views Asked by At

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

1

There are 1 answers

0
juliomalves On

You can use Next.js middleware to dynamically redirect the short URLs to their long URLs counterparts.

Unlike redirects in next.config.js that are generated at build time, middleware runs on each request allowing for newly created pages to be redirected to.

Add the following middleware.js file at the same level as the pages folder.

// middleware.js
import { NextResponse } from 'next/server';
import getTitleById from '<path-to-getTitleById>'; // Replace with your own function

export function middleware(req) {
    // Check if path matches short URL (`/b?id=1` or `b/1`)
    if (req.nextUrl.pathname === '/b' || req.nextUrl.pathname.startsWith('/b/')) {
        // Get `id` from URL path or query parameter
        const [,,idFromPath] = req.nextUrl.pathname.split('/');
        const id = idFromPath ?? req.nextUrl.searchParams.get('id');
        const title = getTitleById(id);

        // If a `title` for given `id` exists, redirect to `/blog/[title]` page
        if (title) {
            return NextResponse.redirect(new URL(`/blog/${title}`, req.url));
        }
    }

    return NextResponse.next();
}

The above will redirect URLs like /b?id=1 or /b/1 to the appropriate /blog/slug-for-id-1, given that getTitleById is able to do that mapping.