Serve the app on app.qrmaster.net, marketing on www

Splits the two hostnames across one deployment. No files move: the Next app still
serves every route on both hosts, and the middleware decides per host which paths it
owns and 301s the rest. /login and /signup stay on www - all 82 marketing CTAs point
at /signup, which carries a hard canonical to www plus ad traffic.

src/lib/hosts.ts is the single source of truth for the boundary (APP_PATH_PREFIXES,
isAppPath, wwwUrl, appUrl, urlForPath). The middleware and every absolute-URL builder
read from it so they cannot drift apart.

- Split the overloaded NEXT_PUBLIC_APP_URL into a www and an app origin. It previously
  fed both public URLs and in-app URLs, so any single value was wrong somewhere. Most
  important: QRCodeCard encodes this origin into the QR code the user downloads and
  prints, so it must stay on www.
- Route Stripe return URLs, email links and OAuth redirects per path rather than
  against one origin, so /dashboard lands on app and /pricing on www.
- Cross the host boundary once, after a successful login: the router cannot push across
  origins, so that jump needs a full load. The user arrives signed in because the
  session cookie is scoped to COOKIE_DOMAIN.
- Keep the app host out of search indexes: X-Robots-Tag on every response plus a
  Disallow-all robots.txt via rewrite, and /sitemap.xml redirects to www.
- Point the TikTok callback fallback at www explicitly. It used to read
  NEXT_PUBLIC_APP_URL, whose meaning changed here, and only the apex domain is
  verified with TikTok.

Host splitting is inert while both origins are equal, so development is unaffected.

Verified: tsc clean, production build succeeds including the Edge middleware bundle,
and the path-to-host mapping is unit-checked (prefix traps like /created and
/settings-guide stay on www, query strings do not break matching).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-12 19:44:08 +02:00
parent 35ea8cc3e9
commit 53ef4b3b91
22 changed files with 383 additions and 63 deletions

View File

@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/Button';
import { useTranslation } from '@/hooks/useTranslation';
import { useCsrf } from '@/hooks/useCsrf';
import { appendRedirectParam, sanitizeRedirectPath } from '@/lib/auth-flow';
import { needsHostChange, urlForPath } from '@/lib/hosts';
type LoginClientProps = {
showPageHeading?: boolean;
@@ -63,6 +64,15 @@ export default function LoginClient({ showPageHeading = true }: LoginClientProps
const redirectUrl = data.needsOnboarding
? appendRedirectParam('/onboarding', redirectTarget)
: (redirectTarget || '/dashboard');
// Login lives on the marketing host, the app on app.*. The router cannot
// push across origins, so a host change needs a full load. The session
// cookie is shared via COOKIE_DOMAIN, so the user arrives signed in.
if (needsHostChange(redirectUrl)) {
window.location.assign(urlForPath(redirectUrl));
return;
}
router.push(redirectUrl);
router.refresh();
} else {

View File

@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/Button';
import { useTranslation } from '@/hooks/useTranslation';
import { useCsrf } from '@/hooks/useCsrf';
import { appendRedirectParam, sanitizeRedirectPath } from '@/lib/auth-flow';
import { needsHostChange, urlForPath } from '@/lib/hosts';
export default function SignupClient() {
const router = useRouter();
@@ -48,15 +49,15 @@ export default function SignupClient() {
body: JSON.stringify({ name, email, password }),
});
const data = await response.json();
if (response.ok && data.success) {
if (data.requiresEmailVerification) {
router.push(`/verify-email?email=${encodeURIComponent(data.email)}`);
return;
}
// Store user in localStorage for client-side
const data = await response.json();
if (response.ok && data.success) {
if (data.requiresEmailVerification) {
router.push(`/verify-email?email=${encodeURIComponent(data.email)}`);
return;
}
// Store user in localStorage for client-side
localStorage.setItem('user', JSON.stringify(data.user));
// Track successful signup with PostHog
@@ -76,8 +77,16 @@ export default function SignupClient() {
console.error('PostHog tracking error:', error);
}
// Redirect to onboarding
router.push(appendRedirectParam('/onboarding', redirectTarget));
// Redirect to onboarding - which lives on the app host, so this normally
// crosses the host boundary and cannot go through the router.
const onboardingUrl = appendRedirectParam('/onboarding', redirectTarget);
if (needsHostChange(onboardingUrl)) {
window.location.assign(urlForPath(onboardingUrl));
return;
}
router.push(onboardingUrl);
router.refresh();
} else {
setError(data.error || 'Failed to create account');

View File

@@ -6,6 +6,7 @@ import {
getCookieDomain,
getFlowCookieOptions,
} from '@/lib/cookieConfig';
import { appUrl, urlForPath, wwwUrl } from '@/lib/hosts';
import { signUserId } from '@/lib/session';
import {
appendRedirectParam,
@@ -40,7 +41,7 @@ export async function GET(request: NextRequest) {
);
}
const redirectUri = `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/google`;
const redirectUri = appUrl('/api/auth/google');
const scope = 'openid email profile';
const redirectTarget = sanitizeRedirectPath(searchParams.get('redirect'));
const oauthState = crypto.randomUUID();
@@ -72,10 +73,10 @@ export async function GET(request: NextRequest) {
try {
if (!state || !savedOauthState || state !== savedOauthState) {
const invalidStateResponse = NextResponse.redirect(
`${process.env.NEXT_PUBLIC_APP_URL}/login?error=google-state-invalid`
wwwUrl('/login?error=google-state-invalid')
);
invalidStateResponse.cookies.delete(GOOGLE_OAUTH_STATE_COOKIE_NAME);
invalidStateResponse.cookies.delete(POST_AUTH_REDIRECT_COOKIE_NAME);
invalidStateResponse.cookies.delete({ name: GOOGLE_OAUTH_STATE_COOKIE_NAME, path: '/', domain: getCookieDomain() });
invalidStateResponse.cookies.delete({ name: POST_AUTH_REDIRECT_COOKIE_NAME, path: '/', domain: getCookieDomain() });
return invalidStateResponse;
}
@@ -89,7 +90,7 @@ export async function GET(request: NextRequest) {
);
}
const redirectUri = `${process.env.NEXT_PUBLIC_APP_URL}/api/auth/google`;
const redirectUri = appUrl('/api/auth/google');
// Exchange code for tokens
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
@@ -220,7 +221,7 @@ export async function GET(request: NextRequest) {
authMethod: 'google',
isNewUser: isNewUser.toString(),
}));
const redirectUrl = new URL(`${process.env.NEXT_PUBLIC_APP_URL}${onboardingTarget}`);
const redirectUrl = new URL(urlForPath(onboardingTarget));
const response = NextResponse.redirect(redirectUrl.toString());
response.cookies.set('userId', signUserId(user.id), getAuthCookieOptions());
@@ -234,7 +235,7 @@ export async function GET(request: NextRequest) {
} catch (error) {
console.error('Google OAuth error:', error);
const errorResponse = NextResponse.redirect(
`${process.env.NEXT_PUBLIC_APP_URL}/login?error=google-signin-failed`
wwwUrl('/login?error=google-signin-failed')
);
errorResponse.cookies.delete({ name: GOOGLE_OAUTH_STATE_COOKIE_NAME, path: '/', domain: getCookieDomain() });
errorResponse.cookies.delete({ name: POST_AUTH_REDIRECT_COOKIE_NAME, path: '/', domain: getCookieDomain() });

View File

@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from 'next/server';
import { wwwUrl } from '@/lib/hosts';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
import { db } from '@/lib/db';
@@ -17,7 +18,9 @@ import { triggerLifecycleScoring } from '@/lib/revops-server';
async function issueVerificationEmail(user: { email: string; name: string | null }) {
const verificationToken = crypto.randomBytes(32).toString('base64url');
const verificationUrl = new URL('/api/auth/verify-email', process.env.NEXT_PUBLIC_APP_URL || 'https://www.qrmaster.net');
// Public link in an outgoing email, so it points at the marketing host. The endpoint
// itself is served on both hosts and redirects into the app afterwards.
const verificationUrl = new URL(wwwUrl('/api/auth/verify-email'));
verificationUrl.searchParams.set('token', verificationToken);
await db.verificationToken.deleteMany({ where: { identifier: user.email } });
@@ -147,7 +150,7 @@ export async function POST(request: NextRequest) {
fbc: request.cookies.get('_fbc')?.value,
fbp: request.cookies.get('_fbp')?.value,
},
eventSourceUrl: `${process.env.NEXT_PUBLIC_APP_URL}/signup`,
eventSourceUrl: wwwUrl('/signup'),
}).catch(console.error);
// Create response

View File

@@ -3,11 +3,13 @@ import { db } from '@/lib/db';
import { getAuthCookieOptions } from '@/lib/cookieConfig';
import { signUserId } from '@/lib/session';
import { sendWelcomeEmail } from '@/lib/email';
import { appUrl, wwwUrl } from '@/lib/hosts';
export async function GET(request: NextRequest) {
const token = new URL(request.url).searchParams.get('token');
const publicAppUrl = process.env.NEXT_PUBLIC_APP_URL || new URL(request.url).origin;
const expiredUrl = new URL('/verify-email?status=expired', publicAppUrl);
// /verify-email is a public page on the marketing host; /onboarding lives on the app
// host. The session cookie is shared across both, so the user stays signed in.
const expiredUrl = new URL(wwwUrl('/verify-email?status=expired'));
if (!token) return NextResponse.redirect(expiredUrl);
@@ -34,7 +36,7 @@ export async function GET(request: NextRequest) {
console.error('Welcome email after verification failed:', error);
}
const response = NextResponse.redirect(new URL('/onboarding?email_verified=1', publicAppUrl));
const response = NextResponse.redirect(appUrl('/onboarding?email_verified=1'));
response.cookies.set('userId', signUserId(user.id), getAuthCookieOptions());
return response;
}

View File

@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { db } from '@/lib/db';
import { cookies } from 'next/headers';
import { appUrl, wwwUrl } from '@/lib/hosts';
export async function POST(request: NextRequest) {
try {
@@ -53,15 +54,16 @@ export async function POST(request: NextRequest) {
customer: customerId,
mode: 'subscription',
payment_method_types: ['card'],
allow_promotion_codes: true,
allow_promotion_codes: true,
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard?success=true`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing?canceled=true`,
// /dashboard is on the app host, /pricing on the marketing host.
success_url: appUrl('/dashboard?success=true'),
cancel_url: wwwUrl('/pricing?canceled=true'),
metadata: {
userId: user.id,
plan,

View File

@@ -3,6 +3,7 @@ import { stripe, STRIPE_PLANS } from '@/lib/stripe';
import { db } from '@/lib/db';
import { getSessionUserId } from '@/lib/session';
import { rateLimit, getClientIdentifier, RateLimits } from '@/lib/rateLimit';
import { urlForPath } from '@/lib/hosts';
export async function POST(request: NextRequest) {
try {
@@ -109,7 +110,11 @@ export async function POST(request: NextRequest) {
});
}
const appUrl = process.env.NEXT_PUBLIC_APP_URL || request.nextUrl.origin;
// Resolved per path rather than against a single origin: safeReturnPath comes from an
// in-app page (/dashboard, /upgrade, ...) and belongs on the app host, while the
// default cancel target /pricing belongs on the marketing host.
const withParam = (path: string, param: string) =>
`${path}${path.includes('?') ? '&' : '?'}${param}`;
// Create Stripe Checkout Session
const checkoutSession = await stripe.checkout.sessions.create({
@@ -123,12 +128,13 @@ export async function POST(request: NextRequest) {
quantity: 1,
},
],
success_url: safeReturnPath
? `${appUrl}${safeReturnPath}${safeReturnPath.includes('?') ? '&' : '?'}success=true&session_id={CHECKOUT_SESSION_ID}`
: `${appUrl}/dashboard?success=true&session_id={CHECKOUT_SESSION_ID}`,
cancel_url: safeReturnPath
? `${appUrl}${safeReturnPath}${safeReturnPath.includes('?') ? '&' : '?'}canceled=true`
: `${appUrl}/pricing?canceled=true`,
success_url: urlForPath(
withParam(
safeReturnPath || '/dashboard',
'success=true&session_id={CHECKOUT_SESSION_ID}'
)
),
cancel_url: urlForPath(withParam(safeReturnPath || '/pricing', 'canceled=true')),
metadata: {
userId: user.id,
plan,

View File

@@ -3,6 +3,7 @@ import { getSessionUserId } from '@/lib/session';
import { stripe } from '@/lib/stripe';
import { db } from '@/lib/db';
import { rateLimit, getClientIdentifier, RateLimits } from '@/lib/rateLimit';
import { appUrl } from '@/lib/hosts';
export async function POST(request: NextRequest) {
try {
@@ -56,7 +57,7 @@ export async function POST(request: NextRequest) {
// Create Stripe Customer Portal session
const portalSession = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/settings`,
return_url: appUrl('/settings'),
});
return NextResponse.json({ url: portalSession.url });

View File

@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { wwwUrl } from '@/lib/hosts';
import {
assertExpectedTiktokAccount,
TIKTOK_ACCOUNT_KEY,
@@ -39,8 +40,10 @@ export async function GET(request: NextRequest) {
return textResponse('TikTok client credentials are not configured.', 500);
}
// Must match the URI used in /api/tiktok/connect - see the note there about the
// verified domain.
const redirectUri =
process.env.TIKTOK_REDIRECT_URI || `${process.env.NEXT_PUBLIC_APP_URL}/api/tiktok/callback`;
process.env.TIKTOK_REDIRECT_URI || wwwUrl('/api/tiktok/callback');
try {
const tokenResponse = await fetch('https://open.tiktokapis.com/v2/oauth/token/', {

View File

@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { TIKTOK_OAUTH_STATE_COOKIE_NAME } from '@/lib/tiktok';
import { wwwUrl } from '@/lib/hosts';
const isProduction = process.env.NODE_ENV === 'production';
@@ -17,8 +18,10 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: 'TIKTOK_CLIENT_KEY not configured' }, { status: 500 });
}
// Falls back to the marketing host on purpose: TikTok only accepts callbacks on the
// verified domain, and app.qrmaster.net is not verified with them.
const redirectUri =
process.env.TIKTOK_REDIRECT_URI || `${process.env.NEXT_PUBLIC_APP_URL}/api/tiktok/callback`;
process.env.TIKTOK_REDIRECT_URI || wwwUrl('/api/tiktok/callback');
const oauthState = crypto.randomUUID();

View File

@@ -1,4 +1,7 @@
import { NextRequest, NextResponse } from 'next/server';
// These landing pages (/vcard, /display, /coupon, /feedback) are public marketing-host
// pages reached straight from a scanned QR code - never the app host.
import { getWwwOrigin } from '@/lib/hosts';
import { db } from '@/lib/db';
import { hashIP } from '@/lib/hash';
import { triggerLifecycleScoring } from '@/lib/revops-server';
@@ -47,7 +50,7 @@ export async function GET(
break;
case 'VCARD':
// For vCard, redirect to display page
const baseUrlVcard = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3050';
const baseUrlVcard = getWwwOrigin();
destination = `${baseUrlVcard}/vcard?firstName=${encodeURIComponent(content.firstName || '')}&lastName=${encodeURIComponent(content.lastName || '')}&email=${encodeURIComponent(content.email || '')}&phone=${encodeURIComponent(content.phone || '')}&organization=${encodeURIComponent(content.organization || '')}&title=${encodeURIComponent(content.title || '')}`;
break;
case 'GEO':
@@ -58,7 +61,7 @@ export async function GET(
break;
case 'TEXT':
// For plain text, redirect to a display page
const baseUrlText = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3050';
const baseUrlText = getWwwOrigin();
destination = `${baseUrlText}/display?text=${encodeURIComponent(content.text || '')}`;
break;
case 'PDF':
@@ -81,12 +84,12 @@ export async function GET(
break;
case 'COUPON':
// Redirect to coupon display page
const baseUrlCoupon = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3050';
const baseUrlCoupon = getWwwOrigin();
destination = `${baseUrlCoupon}/coupon/${slug}`;
break;
case 'FEEDBACK':
// Redirect to feedback form page
const baseUrlFeedback = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3050';
const baseUrlFeedback = getWwwOrigin();
destination = `${baseUrlFeedback}/feedback/${slug}`;
break;
case 'BARCODE':