Skip to content

Instantly share code, notes, and snippets.

@shreyanshp-cactus
Created April 15, 2025 12:34
Show Gist options
  • Select an option

  • Save shreyanshp-cactus/6591599f7d669488e3381da8a5329e64 to your computer and use it in GitHub Desktop.

Select an option

Save shreyanshp-cactus/6591599f7d669488e3381da8a5329e64 to your computer and use it in GitHub Desktop.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
// Get the referrer and target URL
const referrer = request.headers.get('referer') || '';
const url = request.nextUrl.clone();
// Check if this is a navigation to an external site
if (url.pathname.startsWith('/api/outbound')) {
const targetUrl = url.searchParams.get('to');
// Track outbound link
console.log(`Outbound link from ${referrer} to ${targetUrl}`);
// Redirect to the target URL
return NextResponse.redirect(targetUrl);
}
return NextResponse.next();
}
export const config = {
matcher: '/api/outbound/:path*',
};
// hooks/useOutboundLinkTracking.js
import { useEffect } from 'react';
export default function useOutboundLinkTracking() {
useEffect(() => {
const handleLinkClick = (e) => {
const link = e.target.closest('a');
if (!link) return;
const href = link.getAttribute('href');
if (href && (href.startsWith('http') || href.startsWith('//'))) {
// This is an external link
e.preventDefault();
// Do something with the outbound link
console.log('Outbound link clicked:', href);
// Then navigate
setTimeout(() => {
window.open(href, link.target || '_blank');
}, 100);
}
};
document.addEventListener('click', handleLinkClick);
return () => document.removeEventListener('click', handleLinkClick);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment