Skip to main content
Tutorials

The links in your emails should come from your own domain

Someone repointed 2011 Bitly links from Burger King and McDonald's. How to run your own redirect route in Next.js 16, with Prisma.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

On July 24, 2011, Burger King tweeted a link to help people find their nearest restaurant. It was a bit.ly link. On November 15, 2026, at 05:32 UTC, that same link pointed to Wikipedia's list of Nazi concentration camps.

McDonald's got the same treatment 18 minutes earlier, on a tweet from June 2011: its link now went to the Wikipedia article on the September 11 attacks. Other accounts were hit too, Donald Trump's among them.

Nobody broke into Burger King's or McDonald's accounts. The tweets didn't change. Same text, same URL. What changed was where that URL went, and that was never their call. It was Bitly's.

What happened

Ransomnews spotted it by comparing timestamps. Add a + to the end of any Bitly link and you get its creation date and destination. The Burger King and McDonald's links, published in 2011, showed up as created in the early hours of November 15, 2026. Someone had re-registered those exact back-halves (the part after bit.ly/) and given them a new destination.

Bitly acknowledged it on X the same day: an issue had "allowed bad actors to repurpose certain old, inactive links". It suspended the accounts involved and disabled the affected links. It hasn't said how it happened or how many links were taken, and its own help center says a back-half can't be reused. This wasn't the first time either: in February 2025, old Trump links were reported redirecting to memecoin pages.

On November 17, both links point to their original destinations again: Burger King's restaurant locator and a 2011 article about a McDonald's campaign. But their info pages say they were created on November 17, 2026, at 03:25 and 03:39 UTC. A link from 2011 has had three versions in three days, and the brand that posted it made none of them.

What actually broke

It's tempting to file this under "Bitly bug" and move on. But this is simply how a link shortener works. It keeps a table that says "this path goes to this URL", and whoever controls the table controls the destination. If the table changes (a bug, a deleted account, the company shutting down), your links change with it. Google shut down goo.gl and announced that every link would stop working after August 25, 2025. It later backed off and kept only the links that were still in use.

A link you publish stays your responsibility for years. It lives in emails people keep, in PDF invoices, in posts someone quotes, in another project's docs. You can't edit it after the fact. The one thing you control is the domain it goes through.

In a small SaaS, third-party domains sneak in more often than you'd think:

  • The shortener you use so a link fits in a tweet or looks tidy in a PDF.
  • Your email provider's click tracking, which rewrites every link in the message to count clicks.
  • The campaign domain you registered for a launch and will forget to renew in two years.

That last one counts too. Let a domain expire and whoever buys it next inherits every link you ever published on it. Owning the domain only protects you while you keep paying for it, so turn on auto-renew for any domain you've ever used in an email.

Your own redirect route in Next.js 16

The alternative is to run your own shortener inside your app: a /go/[slug] route that looks up the destination in the database and redirects. Two tables and a route handler. The code below uses Prisma and Postgres. The CREA.MBA boilerplate doesn't ship this route, but it drops into its structure without touching anything else.

The model

model Link {
  id          String      @id @default(cuid())
  slug        String      @unique
  destination String
  permanent   Boolean     @default(false)
  disabledAt  DateTime?
  createdAt   DateTime    @default(now())
  clicks      LinkClick[]
}

model LinkClick {
  id        String   @id @default(cuid())
  linkId    String
  link      Link     @relation(fields: [linkId], references: [id])
  referer   String?
  userAgent String?
  createdAt DateTime @default(now())

  @@index([linkId, createdAt])
}

Note disabledAt. When you retire a link, you disable it and keep the row. Delete the row and the slug is free again, so anyone (you in a year, a teammate, a script) can recreate it with a different destination. That's the Bitly incident at the scale of your own app. Once a path is published, it stays reserved.

The route handler

// src/app/go/[slug]/route.ts
import { after, type NextRequest, NextResponse } from 'next/server';

import { db } from '@/lib/db/client';
import { assertSafeDestination } from '@/lib/links/destination';

export async function GET(request: NextRequest, ctx: RouteContext<'/go/[slug]'>) {
  const { slug } = await ctx.params;
  const link = await db.link.findUnique({ where: { slug } });

  if (!link) {
    return new Response('Link not found', { status: 404 });
  }
  if (link.disabledAt) {
    return new Response('This link is no longer available', { status: 410 });
  }

  const destination = assertSafeDestination(link.destination);
  const referer = request.headers.get('referer');
  const userAgent = request.headers.get('user-agent');

  after(() =>
    db.linkClick.create({ data: { linkId: link.id, referer, userAgent } }),
  );

  return NextResponse.redirect(destination, link.permanent ? 308 : 307);
}

Three Next.js 16 details:

  • RouteContext<'/go/[slug]'> is a global type Next generates during next dev, next build or next typegen. It gives you typed params, and params is a promise, so you await it.
  • after() records the click once the response has gone out. The user reaches the destination without waiting on a database write.
  • GET route handlers aren't cached by default. This one also reads the database and params on every request, so it always runs, which is exactly what you want.

One gotcha if you use next-intl. If your proxy.ts sends everything that doesn't start with /api/ through the locale middleware (the boilerplate's does, with localePrefix: 'as-needed'), /go/abc gets treated as a page and rewritten to a localized path that doesn't exist. Add /go/ to the paths the proxy lets through untouched, the same way it handles /api/.

301, 302, 307 or 308

All four redirect. The differences are whether the browser may remember the redirect, and whether it keeps the request method.

Code Permanent Keeps the method When
301 Yes Not guaranteed Legacy; for new links, prefer 308
302 No Not guaranteed Same as 307 in practice for a GET
307 No Yes The default for /go/
308 Yes Yes When the destination will never change

A link to another site is almost always a GET, so the first column is what matters. A 301 or 308 tells the browser the redirect is forever, and the browser may cache it. Next time it goes straight to the destination without touching your server. You lose the click and, worse, you lose the ability to fix the destination for that user if you ever get it wrong.

That's why permanent defaults to false. A 307 costs one database query per click and keeps you in control. Save 308 for things that truly won't move, like an old URL on your own site that has a new home. Next follows the same logic: redirect() returns a 307 and permanentRedirect() a 308.

Fun fact: Bitly serves its links with a 301. Try curl -I on any of them.

Don't build an open redirect

The mistake that turns a redirect route into a security hole is taking the destination from the URL:

https://yourapp.com/go?url=https://whatever-the-attacker-wants.com

That's an open redirect. Anyone can craft a link that starts with your domain and lands on a phishing page. Your domain supplies the trust, the attacker picks the destination. The exact opposite of what you were after.

Two rules prevent it:

  1. The destination only ever comes from the database. The route takes a slug, never a URL.
  2. Validate the destination when you save it and again when you use it. https only, and only hosts you've approved:
// src/lib/links/destination.ts
const ALLOWED_HOSTS = new Set([
  'yourapp.com',
  'docs.yourapp.com',
  'github.com',
]);

export function assertSafeDestination(raw: string): URL {
  const url = new URL(raw);

  if (url.protocol !== 'https:') {
    throw new Error(`Protocol not allowed: ${url.protocol}`);
  }
  if (!ALLOWED_HOSTS.has(url.hostname)) {
    throw new Error(`Host not allowed: ${url.hostname}`);
  }
  return url;
}

An allowlist feels like overkill until someone with admin access (or a bug in the form that creates links) saves a destination they shouldn't. If you genuinely need to link anywhere, at least record who created each link.

Counting clicks honestly

LinkClick gives you clicks per link per day, and it works the same for an email, an invoice or a post. Just know that not every click is a person. Corporate email security scanners open the links in a message before it reaches the inbox, to check whether they're malicious, and every one of those visits counts.

You don't need to solve this completely. Store the user-agent, be suspicious of spikes that arrive seconds after a send, and don't read the raw number as real interest.

What about Resend's click tracking?

If you send email with Resend, click tracking is off by default. When you turn it on, Resend rewrites the links in each email to go through a tracking subdomain, logs the click and forwards the user to the original destination.

The good part: that subdomain is yours. Something like links.yourapp.com, set up with a CNAME record in your DNS, and tracking doesn't work without it. So the link your user sees starts with your domain, and if you ever want Resend out of the loop, you control the DNS and can point it elsewhere.

The part worth knowing is in their own docs. If you remove the domain in Resend, their proxy goes with it and links you've already sent stop working, unless you've set up your own proxy on that subdomain first. And once a tracking subdomain exists, it can be changed but never removed. The domain is yours; the redirect table lives at Resend.

The two approaches aren't mutually exclusive. Resend tracking tells you which recipient clicked what in which email. Your /go/ route gives you links that work the same outside email and whose destination you control. Use both at once and every click takes two hops, so pick one per kind of link.

Takeaways

  • No link you publish should start with a domain you don't control.
  • A /go/[slug] route is two tables and about thirty lines in Next.js 16.
  • Use 307 by default, 308 only when the destination will never change.
  • The destination comes from the database and is checked against an allowlist. Never from the URL.
  • Disable links and keep the row, so nobody can reuse the path.
  • Keep renewing any domain you've used in an email, even after you stop using it.

Burger King did nothing wrong in 2011. It used the tool everyone used to make a link fit in a tweet. Fifteen years later, someone else decided where it went.

How many links in your welcome emails go through a domain that isn't yours today?

Next.jsPrismaEmailSecurityResend

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI