Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

feat: prerender the invoice app and move the Stripe template to /stripe-template (#281)

Vlad Sazonau19f688d05e1c
diff --git a/e2e/about.test.ts b/e2e/about.test.ts
index 564281f..979a591 100644
--- a/e2e/about.test.ts
+++ b/e2e/about.test.ts
@@ -83,7 +83,7 @@ test.describe("About page", () => {
exact: true,
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
// The about page streams behind a `loading.tsx` Suspense boundary. While
// React reveals the boundary, the streamed copy of the content is still
@@ -189,7 +189,7 @@ test.describe("About page", () => {
});
await expect(appLink).toBeVisible();
- await expect(appLink).toHaveAttribute("href", "/?template=default");
+ await expect(appLink).toHaveAttribute("href", "/");
await expect(appLink).not.toHaveAttribute("target", "_blank");
const featuresLink = footerLinks.getByRole("link", {
@@ -332,7 +332,7 @@ test.describe("About page", () => {
});
await expect(appLink).toBeVisible();
- await expect(appLink).toHaveAttribute("href", "/?template=default");
+ await expect(appLink).toHaveAttribute("href", "/");
await expect(appLink).not.toHaveAttribute("target", "_blank");
const featuresLink = footerLinks.getByRole("link", {
@@ -517,7 +517,7 @@ test.describe("About page", () => {
});
await headerGoToAppButton.click();
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
});
// we don't show nav links and language switcher in header on mobile
@@ -609,7 +609,7 @@ test.describe("About page", () => {
exact: true,
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
await expect(
header.getByRole("link", { name: "About Us", exact: true }),
diff --git a/e2e/changelog.test.ts b/e2e/changelog.test.ts
index d45aa32..489be5b 100644
--- a/e2e/changelog.test.ts
+++ b/e2e/changelog.test.ts
@@ -17,7 +17,7 @@ test.describe("Changelog page", () => {
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
// Check main heading
await expect(
@@ -89,7 +89,7 @@ test.describe("Changelog page", () => {
exact: true,
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
// Check that we're on an individual entry page by looking for "Back to All Posts" link
await expect(
diff --git a/e2e/contacts-backup.test.ts b/e2e/contacts-backup.test.ts
index 23cd260..86b2f4c 100644
--- a/e2e/contacts-backup.test.ts
+++ b/e2e/contacts-backup.test.ts
@@ -67,7 +67,7 @@ test.describe("Sellers & buyers backup", () => {
page,
downloadDir,
}) => {
- await page.goto("/?template=default");
+ await page.goto("/");
await page.evaluate(
({ sellersKey, buyersKey, sellers, buyers }) => {
diff --git a/e2e/default-invoice-template/default-invoice-template.test.ts b/e2e/default-invoice-template/default-invoice-template.test.ts
index a7ba192..a04f101 100644
--- a/e2e/default-invoice-template/default-invoice-template.test.ts
+++ b/e2e/default-invoice-template/default-invoice-template.test.ts
@@ -16,8 +16,8 @@ test.describe("Default Invoice Template", () => {
// we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests
await page.clock.setSystemTime(new Date("2025-12-17T00:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
});
test(
@@ -437,7 +437,7 @@ test.describe("Default Invoice Template", () => {
// Navigate back to the previous page
await page.goto("/");
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch back to form tab
await editInvoiceTab.click();
@@ -641,7 +641,7 @@ test.describe("Default Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// Verify that the Stripe template is selected
const templateSelect = page.getByRole("combobox", {
@@ -678,7 +678,7 @@ test.describe("Default Invoice Template", () => {
browserName,
downloadDir,
}) => {
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByTestId("general-information-section");
@@ -711,8 +711,8 @@ test.describe("Default Invoice Template", () => {
*/
// Navigate back and switch to Stripe template to verify logo persists
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
// Verify logo is still present after navigation
const newGeneralInfoSection = page.getByTestId(
@@ -731,7 +731,7 @@ test.describe("Default Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// Verify logo persists after template switch
await expect(
@@ -754,7 +754,7 @@ test.describe("Default Invoice Template", () => {
}, testInfo) => {
const CUSTOM_DATE_OF_SALES_LABEL = "Sale date";
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByTestId("general-information-section");
const servicePeriodFieldset = generalInfoSection.getByRole("group", {
@@ -798,7 +798,7 @@ test.describe("Default Invoice Template", () => {
});
await page.goto("/");
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const newGeneralInfoSection = page.getByTestId(
"general-information-section",
diff --git a/e2e/generate-invoice-link.test.ts b/e2e/generate-invoice-link.test.ts
index db81b46..cc0fc3b 100644
--- a/e2e/generate-invoice-link.test.ts
+++ b/e2e/generate-invoice-link.test.ts
@@ -42,7 +42,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
test.beforeEach(async ({ page }) => {
await page.goto("/");
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
});
test(
@@ -192,14 +192,14 @@ test.describe("Generate Invoice Link (Get link)", () => {
// Get the current URL which should now contain the share data
const sharedUrl = page.url();
- expect(sharedUrl).toContain("?template=default&data=");
+ expect(sharedUrl).toContain("/?data=");
// Open URL in new tab
const newPage = await context.newPage();
await newPage.goto(sharedUrl);
// Verify the URL contains the shared invoice data
- await expect(newPage).toHaveURL(/\?template=default&data=/);
+ await expect(newPage).toHaveURL(/\/\?data=/);
// Get elements from the new page context
const newInvoiceNumberFieldset = newPage.getByRole("group", {
@@ -351,7 +351,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
// Navigate to page with invalid data parameter
await page.goto("/?data=invalid-data-string", { waitUntil: "commit" });
- await expect(page).toHaveURL("/?data=invalid-data-string&template=default");
+ await expect(page).toHaveURL("/?data=invalid-data-string");
// ensure page is loaded
await expect(
@@ -397,7 +397,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
await expect(page.getByText("Try generating a new link.")).toBeHidden();
// Wait for URL to be cleared and verify
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// ensure page content is displayed
await expect(
@@ -413,7 +413,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
// Navigate to page with invalid data parameter
await page.goto("/?data=corrupted-url", { waitUntil: "commit" });
- await expect(page).toHaveURL("/?data=corrupted-url&template=default");
+ await expect(page).toHaveURL("/?data=corrupted-url");
/* Ensure page content is displayed */
@@ -473,7 +473,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
).toBeVisible();
// Wait for URL to be cleared and verify
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
/* Ensure page content is displayed */
@@ -494,9 +494,9 @@ test.describe("Generate Invoice Link (Get link)", () => {
// Navigate to old uncompressed URL
await page.goto(`/?data=${OLD_UNCOMPRESSED_URL}`, { waitUntil: "commit" });
- // Verify the page loads without error
+ // Verify the page loads without error (and moves to the Stripe template's route)
await expect(page).toHaveURL(
- `/?data=${OLD_UNCOMPRESSED_URL}&template=stripe`,
+ `/stripe-template?data=${OLD_UNCOMPRESSED_URL}`,
);
const oldUrl = page.url();
@@ -556,8 +556,11 @@ test.describe("Generate Invoice Link (Get link)", () => {
await page.goto(newCompressedUrl, { waitUntil: "commit" });
- // Verify the page loads without error
- await expect(page).toHaveURL(newCompressedUrl);
+ // Verify the page loads without error: the legacy `/?template=stripe` link is
+ // redirected to the Stripe template's route, which drops the redundant param
+ await expect(page).toHaveURL(
+ newCompressedUrl.replace("/?template=stripe&", "/stripe-template?"),
+ );
const newUrl = page.url();
@@ -696,7 +699,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
// Get the current URL which should now contain the share data
const sharedUrl = page.url();
- expect(sharedUrl).toContain("?template=default&data=");
+ expect(sharedUrl).toContain("/?data=");
/*
* VERIFY SHARED INVOICE DATA IS LOADED IN NEW TAB
@@ -707,7 +710,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
await newPage.goto(sharedUrl);
// Verify the URL contains the shared invoice data
- await expect(newPage).toHaveURL(/\?template=default&data=/);
+ await expect(newPage).toHaveURL(/\/\?data=/);
// Get the invoice number field from the new page
const newInvoiceNumberFieldset = newPage.getByRole("group", {
@@ -781,7 +784,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
).toBeVisible();
// Verify the data parameter is removed from URL after modification
- await expect(newPage).toHaveURL("?template=default");
+ await expect(newPage).toHaveURL("/");
// Verify shared invoice badge is hidden after modification
await expect(newPage.getByTestId("shared-invoice-badge")).toBeHidden();
@@ -986,7 +989,7 @@ test.describe("Generate Invoice Link (Get link)", () => {
).toBeVisible();
// Verify URL was NOT updated with data parameter
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Verify toast is still visible after 2 seconds
await expect(
diff --git a/e2e/how-it-works.test.ts b/e2e/how-it-works.test.ts
index 4f26ffe..3445b35 100644
--- a/e2e/how-it-works.test.ts
+++ b/e2e/how-it-works.test.ts
@@ -25,7 +25,7 @@ test.describe("How it works page", () => {
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
await expect(page.getByTestId("how-it-works-page-title")).toBeVisible();
await expect(
diff --git a/e2e/invoice-app-seo-content.test.ts b/e2e/invoice-app-seo-content.test.ts
new file mode 100644
index 0000000..3198cb0
--- /dev/null
+++ b/e2e/invoice-app-seo-content.test.ts
@@ -0,0 +1,168 @@
+import { expect, test } from "@playwright/test";
+
+import { INITIAL_INVOICE_DATA } from "@/app/constants";
+import { PDF_DATA_LOCAL_STORAGE_KEY } from "@/app/schema";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
+/**
+ * Each invoice app route has its own crawlable copy below the editor: `HomeSeoContent` on
+ * `/` and `StripeTemplateSeoContent` on `/stripe-template`. The two are written for
+ * different queries, so each route must carry its own block and never the other's.
+ */
+
+const ROUTES = [
+ {
+ pathname: "/",
+ testId: "home-seo-content",
+ otherTestId: "stripe-template-seo-content",
+ heading: "A free invoice generator that runs in your browser",
+ },
+ {
+ pathname: STRIPE_TEMPLATE_PATHNAME,
+ testId: "stripe-template-seo-content",
+ otherTestId: "home-seo-content",
+ heading: "A free Stripe-style invoice template",
+ },
+] as const;
+
+test.describe("Invoice app SEO content", () => {
+ for (const { pathname, testId, otherTestId, heading } of ROUTES) {
+ test(`${pathname} serves its own SEO block in the prerendered HTML`, async ({
+ request,
+ }, testInfo) => {
+ // eslint-disable-next-line playwright/no-skipped-test -- HTTP only test, Desktop Chrome only
+ test.skip(
+ testInfo.project.name !== "Desktop Chrome",
+ "the served HTML does not depend on the browser",
+ );
+
+ const response = await request.get(pathname);
+ expect(response.status()).toBe(200);
+
+ // what a crawler gets before any JavaScript runs: the editor is client-only, this is not
+ const html = await response.text();
+ expect(html).toContain(`data-testid="${testId}"`);
+ expect(html).toContain(heading);
+ expect(html).not.toContain(`data-testid="${otherTestId}"`);
+ });
+
+ test(`${pathname} shows its own SEO block below the editor`, async ({
+ page,
+ }) => {
+ await page.goto(pathname);
+
+ const section = page.getByTestId(testId);
+ await expect(section).toBeVisible();
+ await expect(
+ section.getByRole("heading", { level: 2, name: heading }),
+ ).toBeVisible();
+ await expect(section.getByRole("heading", { name: "FAQ" })).toBeVisible();
+
+ await expect(page.getByTestId(otherTestId)).toHaveCount(0);
+ });
+ }
+
+ test("/ links to the Stripe template and the landing pages", async ({
+ page,
+ }) => {
+ await page.goto("/");
+
+ const section = page.getByTestId("home-seo-content");
+
+ await expect(
+ section.getByRole("link", { name: "Stripe-style invoice template" }),
+ ).toHaveAttribute("href", STRIPE_TEMPLATE_PATHNAME);
+ await expect(
+ section.getByRole("link", { name: "no login and no signup" }),
+ ).toHaveAttribute("href", "/invoice-generator-no-login");
+ });
+
+ test("/stripe-template links to the Stripe invoice generator landing, not to itself", async ({
+ page,
+ }) => {
+ await page.goto(STRIPE_TEMPLATE_PATHNAME);
+
+ const section = page.getByTestId("stripe-template-seo-content");
+
+ await expect(
+ section.getByRole("link", { name: "Stripe invoice generator" }),
+ ).toHaveAttribute("href", "/stripe-invoice-alternative");
+ await expect(
+ section.getByRole("link", { name: "there is no signup" }),
+ ).toHaveAttribute("href", "/invoice-generator-no-login");
+ await expect(
+ section.locator(`a[href="${STRIPE_TEMPLATE_PATHNAME}"]`),
+ ).toHaveCount(0);
+ });
+
+ test("/stripe-template 'classic invoice template' opens the default template for a visitor whose invoice uses Stripe", async ({
+ page,
+ }) => {
+ await page.goto(STRIPE_TEMPLATE_PATHNAME);
+
+ // a bare `/` would send this visitor straight back to `/stripe-template`
+ await page.evaluate(
+ ({ invoiceData, storageKey }) => {
+ localStorage.setItem(storageKey, JSON.stringify(invoiceData));
+ },
+ {
+ storageKey: PDF_DATA_LOCAL_STORAGE_KEY,
+ invoiceData: { ...INITIAL_INVOICE_DATA, template: "stripe" },
+ },
+ );
+
+ // `dispatchEvent`, not a real click: Chrome's PDF viewer takes focus when it loads and
+ // scrolls the preview back into view, so a real click can land on the preview
+ await page
+ .getByTestId("stripe-template-seo-content")
+ .getByRole("link", { name: "classic invoice template" })
+ .dispatchEvent("click");
+
+ await expect(page).toHaveURL("/");
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("default");
+ await expect(page.getByTestId("home-seo-content")).toBeVisible();
+ });
+
+ // A template switch rewrites the address bar in place and keeps the server-rendered
+ // block, so the one sentence of it that names a template follows the switch.
+ test("/stripe-template offers the Stripe template back after switching to the default one", async ({
+ page,
+ }) => {
+ await page.goto(STRIPE_TEMPLATE_PATHNAME);
+
+ const section = page.getByTestId("stripe-template-seo-content");
+ await expect(
+ section.getByRole("link", { name: "classic invoice template" }),
+ ).toBeVisible();
+
+ await page
+ .getByRole("combobox", { name: "Invoice Template" })
+ .selectOption("default");
+ await expect(page).toHaveURL("/");
+
+ // the block itself stays, only the sentence changes
+ await expect(section).toBeVisible();
+ await expect(
+ section.getByRole("link", { name: "classic invoice template" }),
+ ).toHaveCount(0);
+
+ const stripeTemplateLink = section.getByRole("link", {
+ name: "Stripe invoice template",
+ exact: true,
+ });
+ await expect(stripeTemplateLink).toHaveAttribute(
+ "href",
+ STRIPE_TEMPLATE_PATHNAME,
+ );
+
+ // `dispatchEvent` for the same PDF viewer focus reason as above
+ await stripeTemplateLink.dispatchEvent("click");
+
+ await expect(page).toHaveURL(STRIPE_TEMPLATE_PATHNAME);
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("stripe");
+ });
+});
diff --git a/e2e/invoice-form.test.ts b/e2e/invoice-form.test.ts
index a59c719..080c0bb 100644
--- a/e2e/invoice-form.test.ts
+++ b/e2e/invoice-form.test.ts
@@ -30,8 +30,8 @@ import { expectYouTubeEmbedToShow } from "./utils/youtube-embed";
test.describe("Invoice Generator Page", () => {
test.beforeEach(async ({ page }) => {
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
});
test("returns permanent redirect from /:locale/app to /", async ({
@@ -51,7 +51,7 @@ test.describe("Invoice Generator Page", () => {
test("displays correct OG meta tags for default template", async ({
page,
}) => {
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const templateCombobox = page.getByRole("combobox", {
name: "Invoice Template",
@@ -95,7 +95,7 @@ test.describe("Invoice Generator Page", () => {
test("displays correct buttons and links in header", async ({ page }) => {
// Check URL is correct
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Check title and branding
await expect(page).toHaveTitle(
@@ -337,7 +337,7 @@ test.describe("Invoice Generator Page", () => {
// because leaving the form tab flushed it. `install()` alone is not enough, the fake
// clock keeps ticking until it is paused.
await page.clock.install();
- await page.goto("/?template=default");
+ await page.goto("/");
// pause ahead of where the page's fake clock already is: `pauseAt` fast forwards to
// the given time and rejects a target that is already in the past, so the margin has
@@ -1738,8 +1738,8 @@ test.describe("Invoice Generator Page", () => {
// we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests
await page.clock.setSystemTime(new Date("2025-12-01T00:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByRole("region", {
name: "General Information",
@@ -1901,8 +1901,8 @@ test.describe("Invoice Generator Page", () => {
}) => {
await page.clock.setSystemTime(new Date("2025-12-01T00:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByRole("region", {
name: "General Information",
@@ -1983,8 +1983,8 @@ test.describe("Invoice Generator Page", () => {
test("allows setting a partial service period", async ({ page }) => {
await page.clock.setSystemTime(new Date("2025-06-15T12:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByRole("region", {
name: "General Information",
diff --git a/e2e/invoice-templates-common/shared-template-features.test.ts b/e2e/invoice-templates-common/shared-template-features.test.ts
index 7771b93..d070790 100644
--- a/e2e/invoice-templates-common/shared-template-features.test.ts
+++ b/e2e/invoice-templates-common/shared-template-features.test.ts
@@ -2,6 +2,7 @@ import type { Locator, Page } from "@playwright/test";
import { INVOICE_PDF_TRANSLATIONS } from "@/app/(main)/(app)/pdf-i18n-translations/pdf-translations";
import type { SupportedTemplates } from "@/app/schema";
+import { buildInvoiceAppUrl } from "@/utils/invoice-app-url";
// IMPORTANT: we use custom extended test fixture that provides a temporary download directory for each test
import { expect, test } from "../utils/extended-playwright-test";
@@ -37,8 +38,8 @@ async function selectTemplate(page: Page, template: Template) {
.selectOption(template);
}
- await page.waitForURL(`/?template=${template}`);
- await expect(page).toHaveURL(`/?template=${template}`);
+ await page.waitForURL(buildInvoiceAppUrl({ template }));
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
}
/**
@@ -260,8 +261,8 @@ test.describe("Invoice Template shared features", () => {
// we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests
await page.clock.setSystemTime(new Date("2025-12-17T00:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
});
for (const template of TEMPLATES) {
@@ -328,7 +329,7 @@ test.describe("Invoice Template shared features", () => {
// navigate back to the previous page
await page.goto("/");
- await expect(page).toHaveURL(`/?template=${template}`);
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
const newFinalSection = page.getByTestId("final-section");
@@ -448,7 +449,7 @@ test.describe("Invoice Template shared features", () => {
});
await page.goto("/");
- await expect(page).toHaveURL(`/?template=${template}`);
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
const newGeneralInfoSection = page.getByTestId(
"general-information-section",
@@ -646,7 +647,7 @@ test.describe("Invoice Template shared features", () => {
*/
await page.goto("/");
- await expect(page).toHaveURL(`/?template=${template}`);
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
// Create seller via dialog with email visible
await waitForPdfRegeneration(page, async () => {
@@ -770,7 +771,7 @@ test.describe("Invoice Template shared features", () => {
// the screenshot leaves the app on about:blank; the invoice comes back from localStorage
await page.goto("/");
- await expect(page).toHaveURL(`/?template=${template}`);
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
const numberFormatSelect = page
.getByRole("group", { name: "Number Format" })
diff --git a/e2e/invoice-templates-common/template-languages.test.ts b/e2e/invoice-templates-common/template-languages.test.ts
index 1930624..4b2a909 100644
--- a/e2e/invoice-templates-common/template-languages.test.ts
+++ b/e2e/invoice-templates-common/template-languages.test.ts
@@ -13,6 +13,7 @@ import {
type SupportedLanguages,
type SupportedTemplates,
} from "@/app/schema";
+import { buildInvoiceAppUrl } from "@/utils/invoice-app-url";
// IMPORTANT: we use custom extended test fixture that provides a temporary download directory for each test
import { expect, test } from "../utils/extended-playwright-test";
@@ -94,8 +95,8 @@ async function selectTemplate(page: Page, template: Template) {
.selectOption(template);
}
- await page.waitForURL(`/?template=${template}`);
- await expect(page).toHaveURL(`/?template=${template}`);
+ await page.waitForURL(buildInvoiceAppUrl({ template }));
+ await expect(page).toHaveURL(buildInvoiceAppUrl({ template }));
}
/**
@@ -135,8 +136,8 @@ test.describe("Invoice Template PDF languages", () => {
// we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests
await page.clock.setSystemTime(new Date("2025-12-17T00:00:00Z"));
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
});
for (const template of TEMPLATES) {
diff --git a/e2e/not-found-page.test.ts b/e2e/not-found-page.test.ts
index 6e5c019..4000399 100644
--- a/e2e/not-found-page.test.ts
+++ b/e2e/not-found-page.test.ts
@@ -19,7 +19,7 @@ test.describe("Not Found page", () => {
await expect(homeLink).toBeVisible();
await homeLink.click();
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
});
test("should display not found page in Spanish under [locale] root layout", async ({
@@ -40,6 +40,6 @@ test.describe("Not Found page", () => {
await expect(homeLink).toBeVisible();
await homeLink.click();
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
});
});
diff --git a/e2e/pdf-generation-error.test.ts b/e2e/pdf-generation-error.test.ts
index d5645da..f82a4c4 100644
--- a/e2e/pdf-generation-error.test.ts
+++ b/e2e/pdf-generation-error.test.ts
@@ -28,7 +28,7 @@ test.describe("PDF generation errors", () => {
test("shows the error toast with recovery steps when the PDF cannot be generated", async ({
page,
}) => {
- await page.goto("/?template=default");
+ await page.goto("/");
// sonner renders the toast into a list item, we scope to it so the
// assertions below cannot pass on text found elsewhere on the page
@@ -56,7 +56,7 @@ test.describe("PDF generation errors", () => {
test("clicking download when no PDF is available explains why", async ({
page,
}) => {
- await page.goto("/?template=default");
+ await page.goto("/");
// wait for the failure to surface before clicking download
await expect(page.getByText("Error Generating PDF Document")).toBeVisible();
@@ -76,7 +76,7 @@ test.describe("PDF generation errors", () => {
});
test("the Stripe template surfaces the same error", async ({ page }) => {
- await page.goto("/?template=stripe");
+ await page.goto("/stripe-template");
await expect(page.getByText("Error Generating PDF Document")).toBeVisible();
});
diff --git a/e2e/seller-buyer-management.test.ts b/e2e/seller-buyer-management.test.ts
index bee3f2c..e51c893 100644
--- a/e2e/seller-buyer-management.test.ts
+++ b/e2e/seller-buyer-management.test.ts
@@ -254,9 +254,9 @@ for (const party of PARTIES) {
test.describe(`${label} management`, () => {
test.beforeEach(async ({ page }) => {
- await page.goto("/?template=default");
+ await page.goto("/");
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
});
test(`create/edit ${party}`, async ({ page }) => {
@@ -1253,8 +1253,8 @@ for (const party of PARTIES) {
},
);
- await page.goto("/?template=default");
- await expect(page).toHaveURL("/?template=default");
+ await page.goto("/");
+ await expect(page).toHaveURL("/");
await openNewPartyDialog(page, party);
diff --git a/e2e/seo-landings.test.ts b/e2e/seo-landings.test.ts
index 376fcab..fda603d 100644
--- a/e2e/seo-landings.test.ts
+++ b/e2e/seo-landings.test.ts
@@ -48,7 +48,7 @@ test.describe("SEO landing pages", () => {
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
await expect(
page.getByRole("heading", { level: 1, name: h1 }),
diff --git a/e2e/shared-invoice-robots.test.ts b/e2e/shared-invoice-robots.test.ts
new file mode 100644
index 0000000..d26d078
--- /dev/null
+++ b/e2e/shared-invoice-robots.test.ts
@@ -0,0 +1,144 @@
+import { expect, test, type APIResponse } from "@playwright/test";
+
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
+/**
+ * Shared invoice links carry the whole invoice (names, addresses, amounts) in `?data=`,
+ * so search engines must never index them.
+ *
+ * The invoice app is prerendered, so its robots meta tag is the same for every query
+ * string (`index, follow` on production): shared links are kept out of the index by the
+ * `X-Robots-Tag` header `next.config.mjs` adds when `?data=` is present. Search engines
+ * combine the header with the meta tags and apply the most restrictive directive, and
+ * that combined result is what these tests check -- the way a crawler sees the response.
+ *
+ * robots.txt, which stops compliant crawlers from fetching these links at all, is
+ * covered by `src/app/__tests__/robots.test.ts`.
+ */
+
+const GOOGLEBOT_USER_AGENT =
+ "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
+
+/**
+ * Compressed invoice data as the app puts it in a shared link. The directives do not
+ * depend on the payload, only on `?data=` being there.
+ */
+const DATA = "N4IgjCBcIGoIIBUQBoQGYohSALFALgE4CuApqg";
+
+const SHARED_INVOICE_URLS = [
+ `/?data=${DATA}`,
+ `/?utm_source=newsletter&data=${DATA}`,
+ `${STRIPE_TEMPLATE_PATHNAME}?data=${DATA}`,
+ `${STRIPE_TEMPLATE_PATHNAME}?utm_source=newsletter&data=${DATA}`,
+ // legacy links, from when the template was a query param
+ `/?template=default&data=${DATA}`,
+ `/?data=${DATA}&template=default`,
+ // redirected to `/stripe-template` with its query string
+ `/?template=stripe&data=${DATA}`,
+] as const;
+
+const APP_URLS = [
+ "/",
+ STRIPE_TEMPLATE_PATHNAME,
+ // legacy link, from when the template was a query param
+ "/?template=default",
+] as const;
+
+test.describe("Shared invoice links are kept out of search engines", () => {
+ // plain HTTP requests, no need to run them once per browser project
+ test.beforeEach(({}, testInfo) => {
+ // eslint-disable-next-line playwright/no-skipped-test -- HTTP only test, Desktop Chrome only
+ test.skip(
+ testInfo.project.name !== "Desktop Chrome",
+ "robots directives do not depend on the browser",
+ );
+ });
+
+ for (const url of SHARED_INVOICE_URLS) {
+ test(`${url.replace(DATA, "<data>")} is served with noindex, nofollow`, async ({
+ request,
+ }) => {
+ const response = await request.get(url, {
+ headers: { "User-Agent": GOOGLEBOT_USER_AGENT },
+ });
+
+ expect(response.status()).toBe(200);
+ // the data survives any redirect, so the directives are checked on the page that has it
+ expect(new URL(response.url()).searchParams.get("data")).toBe(DATA);
+
+ // the header alone is enough, whatever the (prerendered) meta tags say
+ expect(parseDirectives(response.headers()["x-robots-tag"])).toEqual(
+ expect.arrayContaining(["noindex", "nofollow"]),
+ );
+
+ const directives = await getEffectiveRobotsDirectives(response);
+ expect(directives).toContain("noindex");
+ expect(directives).toContain("nofollow");
+ });
+ }
+
+ for (const url of APP_URLS) {
+ test(`${url} does not get the shared-link header`, async ({ request }) => {
+ const response = await request.get(url, {
+ headers: { "User-Agent": GOOGLEBOT_USER_AGENT },
+ });
+
+ expect(response.status()).toBe(200);
+
+ // Guards against the `?data=` rule in `next.config.mjs` matching every request, which
+ // would take the whole app out of the index. Not a plain "no header" check: Vercel
+ // sends its own `X-Robots-Tag: noindex` on preview deployments, which is where this
+ // suite runs in CI -- but never `nofollow`, which only the shared-link rule adds.
+ expect(parseDirectives(response.headers()["x-robots-tag"])).not.toContain(
+ "nofollow",
+ );
+
+ // The meta tags are not checked here either: they are `index, follow` on production
+ // but `noindex, nofollow` on preview deployments.
+ });
+ }
+});
+
+/**
+ * Collects every robots directive a crawler reads from a response: the `X-Robots-Tag`
+ * header plus the `robots` and `googlebot` meta tags, lowercased and split into single
+ * directives (`"noindex, nofollow"` -> `["noindex", "nofollow"]`).
+ *
+ * @param response - The page response.
+ * @returns All directives that apply to Googlebot.
+ */
+async function getEffectiveRobotsDirectives(response: APIResponse) {
+ const html = await response.text();
+
+ const metaContents = [
+ ...html.matchAll(
+ /<meta[^>]+name="(?:robots|googlebot)"[^>]+content="([^"]*)"/gi,
+ ),
+ ].map((match) => {
+ return match[1];
+ });
+
+ return [response.headers()["x-robots-tag"], ...metaContents].flatMap(
+ (value) => {
+ return parseDirectives(value);
+ },
+ );
+}
+
+/**
+ * Splits a robots directive list into single directives. Drops a leading user agent
+ * (`googlebot: noindex`), which `X-Robots-Tag` allows.
+ */
+function parseDirectives(value: string | undefined): string[] {
+ if (!value) {
+ return [];
+ }
+
+ return value
+ .replace(/^\s*[\w-]+\s*:(?!\/)/, "")
+ .split(",")
+ .map((directive) => {
+ return directive.trim().toLowerCase();
+ })
+ .filter(Boolean);
+}
diff --git a/e2e/static-assets.test.ts b/e2e/static-assets.test.ts
index bcce790..d476c7c 100644
--- a/e2e/static-assets.test.ts
+++ b/e2e/static-assets.test.ts
@@ -64,7 +64,7 @@ test.describe("Static assets (fonts, images, videos) should be accessible", () =
});
await page.goto("/");
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
expect(failed).toEqual([]);
});
diff --git a/e2e/stripe-invoice-template/share-logic.test.ts b/e2e/stripe-invoice-template/share-logic.test.ts
index 1f095a0..c1f60b7 100644
--- a/e2e/stripe-invoice-template/share-logic.test.ts
+++ b/e2e/stripe-invoice-template/share-logic.test.ts
@@ -7,14 +7,14 @@ import { uploadLogoFile } from "./utils";
test.describe("Stripe Invoice Sharing Logic", () => {
test.beforeEach(async ({ page }) => {
- await page.goto("/?template=default");
+ await page.goto("/");
});
test("can share invoice with Stripe template and *WITHOUT* logo", async ({
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch to Stripe template
await page
@@ -22,9 +22,9 @@ test.describe("Stripe Invoice Sharing Logic", () => {
.selectOption("stripe");
// Wait for URL to be updated
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// Verify share button is still enabled (no logo uploaded)
const shareButton = page.getByRole("button", {
@@ -41,7 +41,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
return url.searchParams.has("data");
});
const url = page.url();
- expect(url).toContain(`?template=stripe&data=`);
+ expect(url).toContain("/stripe-template?data=");
// Verify data parameter is not empty
const urlObj = new URL(url);
@@ -49,21 +49,22 @@ test.describe("Stripe Invoice Sharing Logic", () => {
expect(dataParam).toBeTruthy();
expect(dataParam).not.toBe("");
- // Verify that the shared URL is not indexed by search engines (to prevent sensitive data from being indexed)
- await expect(page.locator('meta[name="robots"]')).toHaveAttribute(
- "content",
- "noindex, nofollow",
- );
-
// ------------------------------------------------------------
// Open URL in new tab
// ------------------------------------------------------------
const context = page.context();
const newPage = await context.newPage();
- await newPage.goto(url);
+ const newPageResponse = await newPage.goto(url);
+
+ // Verify that the shared URL is not indexed by search engines (to prevent sensitive
+ // data from being indexed). The page is prerendered, so this is a response header
+ // rather than the robots meta tag.
+ expect(newPageResponse?.headers()["x-robots-tag"]).toBe(
+ "noindex, nofollow",
+ );
const newUrl = newPage.url();
- expect(newUrl).toContain(`?template=stripe&data=`);
+ expect(newUrl).toContain("/stripe-template?data=");
// Verify data parameter is not empty
const newUrlObj = new URL(newUrl);
@@ -71,12 +72,6 @@ test.describe("Stripe Invoice Sharing Logic", () => {
expect(newDataParam).toBeTruthy();
expect(newDataParam).not.toBe("");
- // Verify that the shared URL is not indexed by search engines (to prevent sensitive data from being indexed)
- await expect(newPage.locator('meta[name="robots"]')).toHaveAttribute(
- "content",
- "noindex, nofollow",
- );
-
// Verify stripe template UI elements are visible
const newPageGeneralInfoSection = newPage.getByTestId(
"general-information-section",
@@ -118,7 +113,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch to Stripe template
await page
@@ -157,7 +152,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch to Stripe template and upload logo
await page
@@ -213,7 +208,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
});
const url = page.url();
- expect(url).toContain(`?template=stripe&data=`);
+ expect(url).toContain("/stripe-template?data=");
// Verify data parameter is not empty
const urlObj = new URL(url);
@@ -226,7 +221,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Start with default template and verify share button is enabled
const shareButton = page.getByRole("button", {
@@ -264,16 +259,81 @@ test.describe("Stripe Invoice Sharing Logic", () => {
await expect(shareButton).toBeEnabled();
});
+ test("switching templates after sharing clears the shared link from the URL", async ({
+ page,
+ }) => {
+ await expect(page).toHaveURL("/");
+
+ const shareButton = page.getByRole("button", { name: "Get link" });
+ const templateSelect = page.getByRole("combobox", {
+ name: "Invoice Template",
+ });
+
+ // The toast actually on screen. The app shows one at a time (`visibleToasts={1}`); the
+ // ones behind it, and one on its way out, are still in the DOM -- and only hidden with
+ // opacity, which `toBeVisible()` does not treat as hidden.
+ const frontToast = page.locator(
+ '[data-sonner-toast][data-front="true"]:not([data-removed="true"])',
+ );
+
+ // Mobile projects share through `navigator.share`, not the clipboard. Keep that share
+ // sheet "open" forever: headless Chrome rejects the call, and the app would then swap the
+ // link's toast for "Failed to share invoice" before the assertion below sees it.
+ await page.evaluate(() => {
+ if (navigator.share) {
+ // A promise that never settles: the user is still looking at the share sheet.
+ const shareSheetLeftOpen = Promise.withResolvers<void>().promise;
+ navigator.share = () => {
+ return shareSheetLeftOpen;
+ };
+ }
+ });
+
+ // Share on the default template...
+ await shareButton.click();
+ await page.waitForURL((url) => {
+ return url.searchParams.has("data");
+ });
+ expect(page.url()).toContain("/?data=");
+
+ // ...then switch to Stripe: the invoice no longer matches the shared link, so `?data=`
+ // has to go. (The template-to-URL sync used to put it back, reading the URL from the
+ // render before the switch.)
+ await templateSelect.selectOption("stripe");
+
+ await expect(page).toHaveURL("/stripe-template");
+ await expect(frontToast).toContainText("Invoice Updated");
+
+ // Same the other way round: share on Stripe, switch back to default. A second round in
+ // one session used to show the stale toasts: "Invoice Updated" stayed in front of the new
+ // link's toast, and then the second "Invoice Updated" never appeared at all.
+ await shareButton.click();
+ await page.waitForURL((url) => {
+ return url.searchParams.has("data");
+ });
+ expect(page.url()).toContain("/stripe-template?data=");
+ // The new link's toast: "...copied to clipboard!" on desktop, "...Share it now." on
+ // mobile. Both carry the same description.
+ await expect(
+ frontToast.getByTestId("share-invoice-link-description-toast"),
+ ).toBeVisible();
+
+ await templateSelect.selectOption("default");
+
+ await expect(page).toHaveURL("/");
+ await expect(frontToast).toContainText("Invoice Updated");
+ });
+
test("preserves sharing state after page reload", async ({ page }) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch to Stripe template and upload logo
await page
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// Upload logo
await uploadLogoFile(page);
@@ -307,7 +367,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
// Reload the page
await page.reload();
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// Verify state persists after reload
await expect(
@@ -333,7 +393,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
);
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Verify share button is visible and enabled in mobile
const shareButton = page.getByRole("button", {
@@ -380,14 +440,14 @@ test.describe("Stripe Invoice Sharing Logic", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Switch to Stripe template
await page
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// Locate the Net Price input for the first invoice item
const netPriceInput = page.locator("#itemNetPrice0");
@@ -437,7 +497,7 @@ test.describe("Stripe Invoice Sharing Logic", () => {
return url.searchParams.has("data");
});
const url = page.url();
- expect(url).toContain("?template=stripe&data=");
+ expect(url).toContain("/stripe-template?data=");
// Verify data parameter is not empty
const urlObj = new URL(url);
diff --git a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts
index 1aae87a..6f85e32 100644
--- a/e2e/stripe-invoice-template/stripe-invoice-template.test.ts
+++ b/e2e/stripe-invoice-template/stripe-invoice-template.test.ts
@@ -1,3 +1,6 @@
+import type { Page } from "@playwright/test";
+
+import { APP_PAGE_TITLE } from "@/app/(main)/(app)/app-page-heading";
import { INITIAL_INVOICE_DATA } from "@/app/constants";
import {
DEFAULT_DATE_FORMAT,
@@ -20,7 +23,7 @@ test.describe("Stripe Invoice Template", () => {
// we set the system time to a fixed date, so that the invoice number and other dates are consistent across tests
await page.clock.setSystemTime(new Date("2025-12-17T00:00:00Z"));
- await page.goto("/?template=default");
+ await page.goto("/");
});
test("uses template-specific default invoice number labels", async ({
@@ -41,7 +44,7 @@ test.describe("Stripe Invoice Template", () => {
},
);
- await page.goto("/?template=stripe");
+ await page.goto("/stripe-template");
const generalInfoSection = page.getByTestId("general-information-section");
const invoiceNumberFieldset = generalInfoSection.getByRole("group", {
@@ -71,11 +74,11 @@ test.describe("Stripe Invoice Template", () => {
test("displays correct OG meta tags for Stripe template", async ({
page,
}) => {
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
// Navigate to Stripe template
- await page.goto("/?template=stripe");
- await expect(page).toHaveURL("/?template=stripe");
+ await page.goto("/stripe-template");
+ await expect(page).toHaveURL("/stripe-template");
const templateCombobox = page.getByRole("combobox", {
name: "Invoice Template",
@@ -97,7 +100,8 @@ test.describe("Stripe Invoice Template", () => {
page.locator('meta[property="og:description"]'),
).toHaveAttribute(
"content",
- "Create professional PDF invoices online for free. Customize invoice templates, add your logo, download instantly, and send invoices without signup.",
+ // the route has its own description, not `/`'s
+ "Free Stripe invoice template. Fill in a Stripe-style invoice, add your logo and a Pay online link, and download the PDF. No Stripe account, no signup.",
);
await expect(page.locator('meta[property="og:site_name"]')).toHaveAttribute(
"content",
@@ -121,7 +125,7 @@ test.describe("Stripe Invoice Template", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const generalInfoSection = page.getByTestId("general-information-section");
@@ -145,7 +149,7 @@ test.describe("Stripe Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// Logo section should still be visible on Stripe template
await expect(
@@ -336,7 +340,7 @@ test.describe("Stripe Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
const generalInfoSection = page.getByTestId("general-information-section");
const paymentUrlInput = generalInfoSection.getByRole("textbox", {
@@ -382,7 +386,7 @@ test.describe("Stripe Invoice Template", () => {
.selectOption("stripe");
// Wait for URL to be updated
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
const generalInfoSection = page.getByTestId("general-information-section");
@@ -423,7 +427,7 @@ test.describe("Stripe Invoice Template", () => {
// Reload page
await page.reload();
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// Verify template is still Stripe
await expect(
@@ -446,7 +450,7 @@ test.describe("Stripe Invoice Template", () => {
test("Signature fields only appears for default template", async ({
page,
}) => {
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const finalSection = page.getByTestId("final-section");
@@ -501,7 +505,7 @@ test.describe("Stripe Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
/** VERIFY SIGNATURE FIELDS ARE NOW HIDDEN */
@@ -526,7 +530,7 @@ test.describe("Stripe Invoice Template", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const invoiceItemsSection = page.getByTestId("invoice-items-section");
@@ -650,7 +654,7 @@ test.describe("Stripe Invoice Template", () => {
.selectOption("stripe");
// Wait for URL to be updated
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// All switches and Type of GTU field should now be hidden
await expect(showNumberColumnSwitch).toBeHidden();
@@ -701,7 +705,7 @@ test.describe("Stripe Invoice Template", () => {
page,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const finalSection = page.getByTestId("final-section");
@@ -739,7 +743,7 @@ test.describe("Stripe Invoice Template", () => {
.getByRole("combobox", { name: "Invoice Template" })
.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
// Verify Payment Method field is now hidden
await expect(paymentMethodField).toBeHidden();
@@ -760,7 +764,7 @@ test.describe("Stripe Invoice Template", () => {
test("shows the service period in the PDF for Stripe and hides it for default", async ({
page,
}) => {
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const templateCombobox = page.getByRole("combobox", {
name: "Invoice Template",
@@ -775,13 +779,13 @@ test.describe("Stripe Invoice Template", () => {
await expect(servicePeriodSwitch).not.toBeChecked();
await templateCombobox.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
await expect(servicePeriodSwitch).toBeChecked();
// switching back restores the default template's own behaviour
await templateCombobox.selectOption("default");
- await page.waitForURL("/?template=default");
+ await page.waitForURL("/");
await expect(servicePeriodSwitch).not.toBeChecked();
@@ -790,11 +794,11 @@ test.describe("Stripe Invoice Template", () => {
await expect(servicePeriodSwitch).toBeChecked();
await templateCombobox.selectOption("stripe");
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
await expect(servicePeriodSwitch).toBeChecked();
await templateCombobox.selectOption("default");
- await page.waitForURL("/?template=default");
+ await page.waitForURL("/");
await expect(servicePeriodSwitch).not.toBeChecked();
});
@@ -804,7 +808,7 @@ test.describe("Stripe Invoice Template", () => {
downloadDir,
}) => {
// Verify default template is selected by default
- await expect(page).toHaveURL("/?template=default");
+ await expect(page).toHaveURL("/");
const invoiceItemsSection = page.getByTestId("invoice-items-section");
@@ -846,7 +850,7 @@ test.describe("Stripe Invoice Template", () => {
.selectOption("stripe");
// Wait for URL to be updated
- await page.waitForURL("/?template=stripe");
+ await page.waitForURL("/stripe-template");
const newInvoiceItemsSection = page.getByTestId("invoice-items-section");
@@ -885,7 +889,7 @@ test.describe("Stripe Invoice Template", () => {
// navigate back to the previous page
await page.goto("/");
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// verify that the stripe template is selected
const templateCombobox = page.getByRole("combobox", {
@@ -901,7 +905,7 @@ test.describe("Stripe Invoice Template", () => {
.selectOption("default");
// Wait for URL to be updated
- await page.waitForURL("/?template=default");
+ await page.waitForURL("/");
const newVatInput = page.getByRole("textbox", {
name: "VAT Rate",
@@ -941,7 +945,7 @@ test.describe("Stripe Invoice Template", () => {
.selectOption("stripe");
// Wait for URL to be updated
- await expect(page).toHaveURL("/?template=stripe");
+ await expect(page).toHaveURL("/stripe-template");
// Upload a valid logo
await uploadLogoFile(page);
@@ -1048,8 +1052,8 @@ test.describe("Stripe Invoice Template", () => {
},
);
- await page.goto("/?template=stripe");
- await expect(page).toHaveURL("/?template=stripe");
+ await page.goto("/stripe-template");
+ await expect(page).toHaveURL("/stripe-template");
await expectPdfScreenshot(page, {
downloadDir,
@@ -1058,4 +1062,202 @@ test.describe("Stripe Invoice Template", () => {
});
});
}
+
+ test("'Open app' takes a returning visitor back to their last template", async ({
+ page,
+ }) => {
+ await expect(page).toHaveURL("/");
+ await expect(page).toHaveTitle(APP_PAGE_TITLE.default);
+
+ await page
+ .getByRole("combobox", { name: "Invoice Template" })
+ .selectOption("stripe");
+ await expect(page).toHaveURL("/stripe-template");
+ // the switch only rewrites the URL, so the page sets the title itself
+ await expect(page).toHaveTitle(APP_PAGE_TITLE.stripe);
+ // and the canonical, which is what Safari's own Share copies
+ await expectCanonicalPathname({ page, pathname: "/stripe-template" });
+
+ // the template is saved with a debounce
+ await expect
+ .poll(() => {
+ return page.evaluate((key) => {
+ const storedData = localStorage.getItem(key);
+
+ return storedData
+ ? (JSON.parse(storedData) as InvoiceData).template
+ : null;
+ }, PDF_DATA_LOCAL_STORAGE_KEY);
+ })
+ .toBe("stripe");
+
+ await page.goto("/changelog");
+
+ // "Open app" links to a bare `/`, which follows the saved template
+ await page
+ .locator("header")
+ .getByRole("link", { name: "Open app", exact: true })
+ .click();
+
+ await expect(page).toHaveURL("/stripe-template");
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("stripe");
+ });
+
+ test("a legacy /?template=default link still opens the default template", async ({
+ page,
+ }) => {
+ await page.evaluate(
+ ({ invoiceData, storageKey }) => {
+ localStorage.setItem(storageKey, JSON.stringify(invoiceData));
+ },
+ {
+ storageKey: PDF_DATA_LOCAL_STORAGE_KEY,
+ invoiceData: { ...INITIAL_INVOICE_DATA, template: "stripe" },
+ },
+ );
+
+ // the param overrides the saved Stripe template, then drops out of the address bar
+ await page.goto("/?template=default");
+
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("default");
+ await expect(page).toHaveURL("/");
+ });
+
+ // A template switch moves the address bar between `/` and `/stripe-template` with
+ // `history.replaceState`, so the router still holds the route the page was loaded on. A
+ // client-side navigation back to that route used to reuse the mounted editor: the URL
+ // changed, the template did not. The footer links to the app's routes are full page loads,
+ // which is what these tests check for: a document request, which a client-side navigation
+ // never makes.
+ //
+ // The links are clicked with `dispatchEvent`: the template switch regenerates the PDF, and
+ // Chrome's PDF viewer takes focus when it loads, scrolling the preview back into view --
+ // a real click in that moment lands on the preview instead of the footer.
+ test("footer 'Free Stripe Invoice Template' opens the Stripe template after switching away from it", async ({
+ page,
+ }) => {
+ await page.goto("/stripe-template");
+
+ await page
+ .getByRole("combobox", { name: "Invoice Template" })
+ .selectOption("default");
+ await expect(page).toHaveURL("/");
+ await expect(page).toHaveTitle(APP_PAGE_TITLE.default);
+ await expectCanonicalPathname({ page, pathname: "/" });
+
+ const stripeTemplateDocumentRequest = waitForDocumentRequest({
+ page,
+ pathname: "/stripe-template",
+ });
+
+ await page
+ .locator("footer")
+ .getByRole("link", { name: "Free Stripe Invoice Template" })
+ .dispatchEvent("click");
+
+ await stripeTemplateDocumentRequest;
+
+ await expect(page).toHaveURL("/stripe-template");
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("stripe");
+ });
+
+ test("footer 'Invoice Generator' opens the template just picked on the page", async ({
+ page,
+ }) => {
+ await expect(page).toHaveURL("/");
+
+ await page
+ .getByRole("combobox", { name: "Invoice Template" })
+ .selectOption("stripe");
+ await expect(page).toHaveURL("/stripe-template");
+
+ // the template is saved with a debounce
+ await expect
+ .poll(() => {
+ return page.evaluate((key) => {
+ const storedData = localStorage.getItem(key);
+
+ return storedData
+ ? (JSON.parse(storedData) as InvoiceData).template
+ : null;
+ }, PDF_DATA_LOCAL_STORAGE_KEY);
+ })
+ .toBe("stripe");
+
+ // The address bar already says `/stripe-template`, so the request also keeps the
+ // assertions below from passing before the navigation has even started.
+ const rootDocumentRequest = waitForDocumentRequest({ page, pathname: "/" });
+
+ await page
+ .locator("footer")
+ .getByRole("link", { name: "Invoice Generator", exact: true })
+ .dispatchEvent("click");
+
+ await rootDocumentRequest;
+
+ // a bare `/` follows the saved template, so this lands back on `/stripe-template`
+ await expect(page).toHaveURL("/stripe-template");
+ await expect(
+ page.getByRole("combobox", { name: "Invoice Template" }),
+ ).toHaveValue("stripe");
+ // loaded as `/`, whose prerendered title and canonical are the default template's
+ await expect(page).toHaveTitle(APP_PAGE_TITLE.stripe);
+ await expectCanonicalPathname({ page, pathname: "/stripe-template" });
+ });
});
+
+interface ExpectCanonicalPathnameParams {
+ page: Page;
+ /** The pathname the canonical URL should point at, e.g. `/stripe-template`. */
+ pathname: string;
+}
+
+/**
+ * Asserts the path of `<link rel="canonical">`. Only the path: the origin is `APP_URL`,
+ * which differs between the dev server and a deployment.
+ */
+async function expectCanonicalPathname({
+ page,
+ pathname,
+}: ExpectCanonicalPathnameParams) {
+ await expect
+ .poll(() => {
+ return page.evaluate(() => {
+ const href = document
+ .querySelector('link[rel="canonical"]')
+ ?.getAttribute("href");
+
+ return href ? new URL(href).pathname : null;
+ });
+ })
+ .toBe(pathname);
+}
+
+interface WaitForDocumentRequestParams {
+ page: Page;
+ /** The pathname the document is requested for, e.g. `/stripe-template`. */
+ pathname: string;
+}
+
+/**
+ * Resolves on the next document request for `pathname`: a full page load, which a
+ * client-side navigation (a fetch of the RSC payload) never makes.
+ */
+function waitForDocumentRequest({
+ page,
+ pathname,
+}: WaitForDocumentRequestParams) {
+ return page.waitForRequest((request) => {
+ return (
+ request.isNavigationRequest() &&
+ request.frame() === page.mainFrame() &&
+ new URL(request.url()).pathname === pathname
+ );
+ });
+}
diff --git a/e2e/tos.test.ts b/e2e/tos.test.ts
index 73ea0eb..e3700e6 100644
--- a/e2e/tos.test.ts
+++ b/e2e/tos.test.ts
@@ -16,7 +16,7 @@ test.describe("Terms of Service page", () => {
});
await expect(goToAppButton).toBeVisible();
- await expect(goToAppButton).toHaveAttribute("href", "/?template=default");
+ await expect(goToAppButton).toHaveAttribute("href", "/");
await expect(page).toHaveTitle("Terms of Service | EasyInvoicePDF");
diff --git a/knip.ts b/knip.ts
index 6e3eb2f..c4bb378 100644
--- a/knip.ts
+++ b/knip.ts
@@ -12,7 +12,6 @@ const config: KnipConfig = {
ignoreDependencies: [
"shadcn",
"@radix-ui/react-separator",
- "@types/ua-parser-js",
"file-saver",
"jszip",
"@types/file-saver",
diff --git a/messages/es.json b/messages/es.json
index d55f301..c8f5c6b 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -2,7 +2,7 @@
"Metadata": {
"about": {
"title": "Generador gratuito de facturas PDF - Sobre EasyInvoicePDF",
- "description": "EasyInvoicePDF en resumen: facturas PDF gratis, vista previa en vivo, privacidad en el navegador, plantillas y enlaces para compartir. Código abierto, sin registro.",
+ "description": "EasyInvoicePDF en resumen: facturas PDF gratis, vista previa en vivo, datos en tu navegador, plantillas y enlaces para compartir. Código abierto, sin registro.",
"keywords": "generador de facturas gratis, factura PDF online, herramienta de facturación, software de facturación, factura open source",
"siteName": "EasyInvoicePDF.com | Generador de Facturas Gratuito"
}
diff --git a/messages/fr.json b/messages/fr.json
index 6a2d52a..b510cc9 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -82,7 +82,7 @@
},
"Metadata": {
"about": {
- "title": "Générateur de factures PDF gratuit - À propos d'EasyInvoicePDF",
+ "title": "Générateur de factures PDF gratuit - EasyInvoicePDF",
"description": "EasyInvoicePDF en bref : factures PDF gratuites, aperçu en direct, traitement dans le navigateur, modèles et liens partageables. Open source, sans inscription.",
"keywords": "générateur de factures gratuit, facture PDF en ligne, outil de facturation, logiciel de facturation, facture open source",
"siteName": "EasyInvoicePDF.com | Générateur de Factures Gratuit"
diff --git a/messages/it.json b/messages/it.json
index 1bf94cb..2901940 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -1,8 +1,8 @@
{
"Metadata": {
"about": {
- "title": "Generatore gratuito di fatture PDF - Informazioni su EasyInvoicePDF",
- "description": "EasyInvoicePDF in sintesi: fatture PDF gratuite, anteprima in tempo reale, elaborazione nel browser, modelli e link condivisibili. Open source, senza registrazione.",
+ "title": "Generatore gratuito di fatture PDF - EasyInvoicePDF",
+ "description": "EasyInvoicePDF in sintesi: fatture PDF gratuite, anteprima dal vivo, elaborazione nel browser, modelli e link condivisibili. Open source, senza registrazione.",
"keywords": "generatore di fatture gratuito, fattura PDF online, strumento di fatturazione, software di fatturazione, fattura open source",
"siteName": "EasyInvoicePDF.com | Generatore di Fatture Gratuito"
}
diff --git a/messages/nb.json b/messages/nb.json
index 79c8a87..fba4b2b 100644
--- a/messages/nb.json
+++ b/messages/nb.json
@@ -1,8 +1,8 @@
{
"Metadata": {
"about": {
- "title": "Om EasyInvoicePDF – gratis fakturagenerator med åpen kildekode",
- "description": "Se hvordan EasyInvoicePDF hjelper frilansere og småbedrifter med å lage profesjonelle PDF-fakturaer gratis – åpen kildekode, personvern først, ingen registrering.",
+ "title": "Om EasyInvoicePDF – gratis fakturagenerator, åpen kildekode",
+ "description": "Se hvordan EasyInvoicePDF hjelper frilansere og småbedrifter med å lage PDF-fakturaer gratis – åpen kildekode, personvern først, ingen registrering.",
"keywords": "gratis fakturagenerator, lage PDF-faktura, fakturaverktøy på nett, faktureringsprogram, fakturagenerator med åpen kildekode",
"siteName": "EasyInvoicePDF.com | Gratis fakturagenerator"
}
diff --git a/messages/pl.json b/messages/pl.json
index 651d59b..1ce810a 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -2,7 +2,7 @@
"Metadata": {
"about": {
"title": "Darmowy generator faktur PDF – o EasyInvoicePDF",
- "description": "EasyInvoicePDF w skrócie: darmowe faktury PDF, podgląd na żywo, dane przetwarzane w przeglądarce, szablony i linki do udostępniania. Open source, bez rejestracji.",
+ "description": "EasyInvoicePDF w skrócie: darmowe faktury PDF, podgląd na żywo, dane w przeglądarce, szablony i linki do udostępniania. Open source, bez rejestracji.",
"keywords": "darmowy generator faktur, faktura PDF online, narzędzie do faktur, oprogramowanie billingowe, faktura open source",
"siteName": "EasyInvoicePDF.com | Darmowy Generator Faktur"
}
diff --git a/messages/sv.json b/messages/sv.json
index b87e23b..9979042 100644
--- a/messages/sv.json
+++ b/messages/sv.json
@@ -1,7 +1,7 @@
{
"Metadata": {
"about": {
- "title": "Om EasyInvoicePDF – gratis fakturagenerator med öppen källkod",
+ "title": "Om EasyInvoicePDF – gratis fakturagenerator, öppen källkod",
"description": "Läs hur EasyInvoicePDF hjälper frilansare och småföretag att skapa professionella PDF-fakturor gratis – öppen källkod, integritet först, ingen registrering.",
"keywords": "gratis fakturagenerator, skapa PDF-faktura, fakturaverktyg online, faktureringsprogram, fakturagenerator med öppen källkod",
"siteName": "EasyInvoicePDF.com | Gratis fakturagenerator"
diff --git a/next.config.mjs b/next.config.mjs
index 18cb869..ee9c7ef 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -186,6 +186,21 @@ const nextConfig = {
},
];
},
+ async headers() {
+ // The invoice app routes are prerendered, so their robots meta tags cannot depend on
+ // the query string. Shared invoice links (`?data=`) are kept out of the index with this
+ // header instead. A crawler always requests the link itself, so it always gets the
+ // header -- the `?data=` that sharing adds in place (`history.replaceState`) only ever
+ // exists in the sharer's own tab.
+ // Keep the paths in sync with `STRIPE_TEMPLATE_PATHNAME` in `src/utils/invoice-app-url.ts`.
+ return ["/", "/stripe-template"].map((source) => {
+ return {
+ source,
+ has: [{ type: "query", key: "data" }],
+ headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow" }],
+ };
+ });
+ },
async redirects() {
return [
// Redirect all /:locale/app requests to the root, because we changed the structure of the app
@@ -194,6 +209,15 @@ const nextConfig = {
destination: "/",
permanent: true,
},
+ // The Stripe template moved from `/?template=stripe` to its own route. The query string
+ // is passed through (so `?data=` share links keep working); the app drops the leftover
+ // `?template=stripe` on the client.
+ {
+ source: "/",
+ has: [{ type: "query", key: "template", value: "stripe" }],
+ destination: "/stripe-template",
+ permanent: true,
+ },
];
},
};
diff --git a/package.json b/package.json
index c949205..443bcc2 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,6 @@
"@trigger.dev/sdk": "4.5.16",
"@types/mdx": "2.0.13",
"@types/qrcode": "1.5.6",
- "@types/ua-parser-js": "0.7.39",
"@upstash/ratelimit": "2.0.5",
"@upstash/redis": "1.34.6",
"@vercel/functions": "3.5.1",
@@ -107,7 +106,6 @@
"sonner": "1.7.4",
"tailwind-merge": "2.6.0",
"tailwindcss-animate": "1.0.7",
- "ua-parser-js": "2.0.3",
"use-debounce": "10.0.4",
"zod": "4.5.4"
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5e0407d..095b402 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -94,9 +94,6 @@ importers:
'@types/qrcode':
specifier: 1.5.6
version: 1.5.6
- '@types/ua-parser-js':
- specifier: 0.7.39
- version: 0.7.39
'@upstash/ratelimit':
specifier: 2.0.5
version: 2.0.5(@upstash/[email protected])
@@ -199,9 +196,6 @@ importers:
tailwindcss-animate:
specifier: 1.0.7
version: 1.0.7([email protected])
- ua-parser-js:
- specifier: 2.0.3
- version: 2.0.3
use-debounce:
specifier: 10.0.4
version: 10.0.4([email protected])
@@ -3478,9 +3472,6 @@ packages:
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==}
-
resolution: {integrity: sha512-k6Gi8Yyo8EtrNtkHXutUu2corfDf9su95VYVP10aGYMMROM6SAItZi0w1XszA6RtWTHSVp5OeFof37w0IEqCQg==}
@@ -3498,9 +3489,6 @@ packages:
resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-P/oDfpofrdtF5xw433SPALpdSchtJmY7nsJItf8h3KXqOslkbySh8zq4dSWXH2oTjRvJ5PczVEoCZPow6GicLg==}
-
resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}
@@ -3933,9 +3921,6 @@ packages:
resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
-
resolution: {integrity: sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ==}
engines: {node: ^10 || ^12 || >=14}
@@ -4199,10 +4184,6 @@ packages:
resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==}
- resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
- engines: {node: '>= 0.8'}
-
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
@@ -4363,10 +4344,6 @@ packages:
resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
- engines: {node: '>=0.4.0'}
-
resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==}
engines: {node: '>= 0.8'}
@@ -4375,9 +4352,6 @@ packages:
resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-lgdERlL3u0aUdHocoouzT10d9I89VVhk0qNRmll7mXdGfJT1/wqZ2ZLA4oJAjeACPY5fT1wsbq2AT+GkuInsow==}
-
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
@@ -4835,10 +4809,6 @@ packages:
resolution: {integrity: sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==}
- engines: {node: '>= 6'}
-
resolution: {integrity: sha512-7CXJtIIA0zy/u12StsYk25qVKxvdLA2ep2sTNxK3ov0mGNIIDqIvAXDSgTnAfDJFsPfWjuz0WjfYSdpvnLA5Tg==}
engines: {node: '>=18.3.0'}
@@ -5323,9 +5293,6 @@ packages:
resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-9Cbovsa52vNQCjdXOzeQq5CnCbAcRk05aU62K20WO372NrTv0NxibLFCK6lQ4/iZEFdEA3p3t2VNOn8AJ53F5g==}
-
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
@@ -7178,13 +7145,6 @@ packages:
engines: {node: '>=16.20.0'}
hasBin: true
- resolution: {integrity: sha512-RwKDW2p3iyWn4UbaxpP2+VxwqXh0jpvdxsYpZ5j/MLLiQOfbsV5shpgQiw93+KMYQPcteeMQ289MaAFzs3G9pw==}
-
- resolution: {integrity: sha512-LZyXZdNttONW8LjzEH3Z8+6TE7RfrEiJqDKyh0R11p/kxvrV2o9DrT2FGZO+KVNs3k+drcIQ6C3En6wLnzJGpw==}
- hasBin: true
-
resolution: {integrity: sha512-FoSOKV7NEofQSkAefMVHam4ZPKYMxjAydxiV72UFEDNV/YofxjGfiZ2A9pZjdL/lRJzTjcu4PABo1JYJX8N5iQ==}
engines: {node: '>=14'}
@@ -10244,11 +10204,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]':
- dependencies:
- '@types/node': 22.8.1
- form-data: 4.0.2
-
dependencies:
undici-types: 6.19.8
@@ -10267,8 +10222,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -10668,8 +10621,6 @@ snapshots:
-
dependencies:
browserslist: 4.28.9
@@ -10933,10 +10884,6 @@ snapshots:
- dependencies:
- delayed-stream: 1.0.0
-
@@ -11057,14 +11004,10 @@ snapshots:
has-property-descriptors: 1.0.2
object-keys: 1.1.1
-
-
@@ -11743,13 +11686,6 @@ snapshots:
cross-spawn: 7.0.6
signal-exit: 4.1.0
- dependencies:
- asynckit: 0.4.0
- combined-stream: 1.0.8
- es-set-tostringtag: 2.1.0
- mime-types: 2.1.35
-
dependencies:
fd-package-json: 2.0.0
@@ -12286,8 +12222,6 @@ snapshots:
dependencies:
call-bound: 1.0.4
-
@@ -14732,18 +14666,6 @@ snapshots:
'@typescript/typescript-win32-arm64': 7.0.2
'@typescript/typescript-win32-x64': 7.0.2
-
- dependencies:
- '@types/node-fetch': 2.6.12
- detect-europe-js: 0.1.2
- is-standalone-pwa: 0.1.1
- node-fetch: 2.7.0
- ua-is-frozen: 0.1.2
- transitivePeerDependencies:
- - encoding
-
diff --git a/src/app/(components)/footer.tsx b/src/app/(components)/footer.tsx
index ffe0c49..201149c 100644
--- a/src/app/(components)/footer.tsx
+++ b/src/app/(components)/footer.tsx
@@ -3,7 +3,10 @@ import Link from "next/link";
/* eslint-disable @next/next/no-html-link-for-pages */
import { FooterCopyright } from "@/app/(components)/footer-copyright";
import { FooterLaunchBadges } from "@/app/(components)/footer-launch-badges";
-import { SEO_FOOTER_SOLUTION_LINKS } from "@/app/(main)/(seo-landings)/seo-landing-footer-links";
+import {
+ APP_FOOTER_SOLUTION_LINKS,
+ SEO_FOOTER_SOLUTION_LINKS,
+} from "@/app/(main)/(seo-landings)/seo-landing-footer-links";
import { LANGUAGE_TO_NATIVE_LABEL, SUPPORTED_I18N_LOCALES } from "@/app/schema";
import { ProjectLogo } from "@/components/etc/project-logo";
import {
@@ -126,6 +129,19 @@ export function Footer({ links, translations }: FooterProps) {
{solutionsHeading}
</h3>
<ul className="space-y-2">
+ {APP_FOOTER_SOLUTION_LINKS.map(({ href, label }) => {
+ return (
+ <li key={href}>
+ {/* a full page load, see `FooterLinkItem.fullPageLoad` */}
+ <a
+ href={href}
+ className="text-sm text-slate-500 hover:text-slate-900"
+ >
+ {label}
+ </a>
+ </li>
+ );
+ })}
{SEO_FOOTER_SOLUTION_LINKS.map(({ slug, label }) => {
return (
<li key={slug}>
@@ -206,6 +222,15 @@ interface FooterLinkItem {
href: string;
label: string;
external?: boolean;
+ /**
+ * Render a plain `<a>` instead of `next/link`, so following it is a full page load.
+ *
+ * Needed for links to the invoice app's own routes (`/`, `/stripe-template`): a template
+ * switch moves the address bar between them with `history.replaceState`, so the router
+ * still holds the route the page was loaded on. A client-side navigation to that route
+ * reuses the mounted editor, which keeps the old template under the new URL.
+ */
+ fullPageLoad?: boolean;
}
export function FooterLinkGroup({
@@ -224,15 +249,21 @@ export function FooterLinkGroup({
{links.map((link) => {
return (
<li key={`${heading}-${link.label}`}>
- <Link
- href={link.href}
- className={FOOTER_LINK_CLASSNAME}
- {...(link.external
- ? { target: "_blank", rel: "noopener noreferrer" }
- : {})}
- >
- {link.label}
- </Link>
+ {link.fullPageLoad ? (
+ <a href={link.href} className={FOOTER_LINK_CLASSNAME}>
+ {link.label}
+ </a>
+ ) : (
+ <Link
+ href={link.href}
+ className={FOOTER_LINK_CLASSNAME}
+ {...(link.external
+ ? { target: "_blank", rel: "noopener noreferrer" }
+ : {})}
+ >
+ {link.label}
+ </Link>
+ )}
</li>
);
})}
@@ -247,7 +278,7 @@ function DefaultFooterLinks() {
<FooterLinkGroup
heading="Product"
links={[
- { href: "/", label: "Invoice Generator" },
+ { href: "/", label: "Invoice Generator", fullPageLoad: true },
{ href: GITHUB_URL, label: "GitHub", external: true },
{ href: "/how-it-works", label: "How it works" },
{ href: "/changelog", label: "Changelog" },
diff --git a/src/app/(components)/header/animated-go-to-app-btn.tsx b/src/app/(components)/header/animated-go-to-app-btn.tsx
index 0d91590..8681a47 100644
--- a/src/app/(components)/header/animated-go-to-app-btn.tsx
+++ b/src/app/(components)/header/animated-go-to-app-btn.tsx
@@ -20,7 +20,7 @@ export function BlackAnimatedGoToAppBtn({
asChild
data-testid="black-animated-go-to-app-btn"
>
- <Link href="/?template=default" className="flex items-center">
+ <Link href="/" className="flex items-center">
<ArrowRightIcon className="mr-2 size-5 animate-pulse-arrow transition-transform group-hover:scale-110" />
{children}
diff --git a/src/app/(components)/header/go-to-app-button-cta.tsx b/src/app/(components)/header/go-to-app-button-cta.tsx
index b463889..ed3ec6b 100644
--- a/src/app/(components)/header/go-to-app-button-cta.tsx
+++ b/src/app/(components)/header/go-to-app-button-cta.tsx
@@ -7,7 +7,7 @@ import { cn } from "@/lib/utils";
export function GoToAppButton({
className,
children,
- href = "/?template=default",
+ href = "/",
}: {
className?: string;
children?: React.ReactNode;
@@ -35,7 +35,7 @@ export function GoToAppButton({
export function BlackGoToAppButton({
className,
children,
- href = "/?template=default",
+ href = "/",
}: {
className?: string;
children?: React.ReactNode;
diff --git a/src/app/(components)/header/mobile-menu.tsx b/src/app/(components)/header/mobile-menu.tsx
index 6be7072..ccd8345 100644
--- a/src/app/(components)/header/mobile-menu.tsx
+++ b/src/app/(components)/header/mobile-menu.tsx
@@ -180,11 +180,7 @@ export function MobileMenuPanel({
}
asChild
>
- <Link
- href="/?template=default"
- className="flex items-center"
- onClick={close}
- >
+ <Link href="/" className="flex items-center" onClick={close}>
<ArrowRightIcon className="mr-2 size-6 group-hover:scale-110" />
{translations.startInvoicingButtonText}
diff --git a/src/app/(components)/project-logo-description.tsx b/src/app/(components)/project-logo-description.tsx
index 08479c3..21e936b 100644
--- a/src/app/(components)/project-logo-description.tsx
+++ b/src/app/(components)/project-logo-description.tsx
@@ -13,9 +13,9 @@ export function ProjectLogoDescription({
rel="noopener noreferrer"
>
{title || (
- <h1 className="text-balance text-xl font-bold text-slate-800 lg:text-2xl">
+ <p className="text-balance text-xl font-bold text-slate-800 lg:text-2xl">
EasyInvoicePDF
- </h1>
+ </p>
)}
</a>
{description || (
diff --git a/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx b/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx
deleted file mode 100644
index 886e315..0000000
--- a/src/app/(main)/(app)/__tests__/robots-meta-sync.test.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-// @vitest-environment happy-dom
-
-import { cleanup, render } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-let currentSearchParams = new URLSearchParams();
-
-vi.mock("next/navigation", () => {
- return {
- useSearchParams: () => {
- return currentSearchParams;
- },
- };
-});
-
-import { RobotsMetaSync } from "../robots-meta-sync";
-
-/**
- * Renders the robots meta tags the way `generateMetadata` does on the server, so the
- * component has something to patch.
- *
- * @param content - The `content` value both tags start out with.
- */
-function renderServerRobotsMeta(content: string) {
- for (const name of ["robots", "googlebot"]) {
- const meta = document.createElement("meta");
- meta.setAttribute("name", name);
- meta.setAttribute("content", content);
- document.head.append(meta);
- }
-}
-
-function robotsMetaContents() {
- return [...document.head.querySelectorAll("meta[name]")].map((meta) => {
- return [meta.getAttribute("name"), meta.getAttribute("content")];
- });
-}
-
-describe("RobotsMetaSync", () => {
- beforeEach(() => {
- currentSearchParams = new URLSearchParams();
- document.head.innerHTML = "";
- });
-
- afterEach(() => {
- cleanup();
- });
-
- it("marks a shared invoice as noindex, nofollow", () => {
- renderServerRobotsMeta("index, follow");
- currentSearchParams = new URLSearchParams("template=stripe&data=abc123");
-
- render(<RobotsMetaSync isIndexableEnvironment={true} />);
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "noindex, nofollow"],
- ["googlebot", "noindex, nofollow"],
- ]);
- });
-
- it("leaves the page indexable when there is no shared data", () => {
- renderServerRobotsMeta("index, follow");
- currentSearchParams = new URLSearchParams("template=stripe");
-
- render(<RobotsMetaSync isIndexableEnvironment={true} />);
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "index, follow"],
- ["googlebot", "index, follow"],
- ]);
- });
-
- it("keeps non-production deployments out of the index entirely", () => {
- renderServerRobotsMeta("noindex, nofollow");
-
- render(<RobotsMetaSync isIndexableEnvironment={false} />);
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "noindex, nofollow"],
- ["googlebot", "noindex, nofollow"],
- ]);
- });
-
- it("re-indexes the page when the shared data is dropped from the URL", () => {
- renderServerRobotsMeta("index, follow");
- currentSearchParams = new URLSearchParams("data=abc123");
-
- const { rerender } = render(
- <RobotsMetaSync isIndexableEnvironment={true} />,
- );
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "noindex, nofollow"],
- ["googlebot", "noindex, nofollow"],
- ]);
-
- // the app drops `?data=` in place too (corrupted link, edits to a shared invoice),
- // which leaves the visitor on `/` -- the canonical page we do want indexed
- currentSearchParams = new URLSearchParams();
- rerender(<RobotsMetaSync isIndexableEnvironment={true} />);
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "index, follow"],
- ["googlebot", "index, follow"],
- ]);
- });
-
- it("adds the tags when the document was rendered without them", () => {
- currentSearchParams = new URLSearchParams("data=abc123");
-
- render(<RobotsMetaSync isIndexableEnvironment={true} />);
-
- expect(robotsMetaContents()).toEqual([
- ["robots", "noindex, nofollow"],
- ["googlebot", "noindex, nofollow"],
- ]);
- });
-
- it("does not add tags to an indexable page that has none", () => {
- render(<RobotsMetaSync isIndexableEnvironment={true} />);
-
- expect(robotsMetaContents()).toEqual([]);
- });
-});
diff --git a/src/app/(main)/(app)/app-page-heading.ts b/src/app/(main)/(app)/app-page-heading.ts
new file mode 100644
index 0000000..f4325d1
--- /dev/null
+++ b/src/app/(main)/(app)/app-page-heading.ts
@@ -0,0 +1,28 @@
+import type { SupportedTemplates } from "@/app/schema";
+
+/**
+ * The `<h1>` of each invoice app route, shown as the tagline under the EasyInvoicePDF logo.
+ *
+ * The brand name above it is a `<p>`: an h1 of "EasyInvoicePDF" told search engines
+ * nothing the domain didn't, while the tagline names what the page is. Rendered by both
+ * the loading skeleton (the only header in the prerendered HTML, since the editor renders
+ * on the client) and the editor's own header, which replaces it -- so the page always has
+ * exactly one h1.
+ *
+ * Kept outside the "use client" header module so the server-rendered skeleton can import
+ * the strings themselves rather than client references.
+ */
+export const APP_PAGE_HEADING = {
+ default: "Free & Open-Source Invoice Generator",
+ stripe: "Free Stripe Invoice Template",
+} as const satisfies Record<SupportedTemplates, string>;
+
+/**
+ * The `<title>` of each invoice app route: the route's metadata on the server, and the tab
+ * title the editor sets on the client when a template switch moves the address bar to the
+ * other route (see `AppPageClient`, which moves the canonical URL along with it).
+ */
+export const APP_PAGE_TITLE = {
+ default: "Free Invoice Generator - Create PDF Invoices Online",
+ stripe: "Stripe Invoice Template - Create Free PDF Invoice",
+} as const satisfies Record<SupportedTemplates, string>;
diff --git a/src/app/(main)/(app)/components/__tests__/invoice-pdf-download-link.test.tsx b/src/app/(main)/(app)/components/__tests__/invoice-pdf-download-link.test.tsx
index dc4fb20..41d6736 100644
--- a/src/app/(main)/(app)/components/__tests__/invoice-pdf-download-link.test.tsx
+++ b/src/app/(main)/(app)/components/__tests__/invoice-pdf-download-link.test.tsx
@@ -216,6 +216,22 @@ describe("InvoicePDFDownloadLink", () => {
expect(link).toHaveClass("pointer-events-none");
});
+ it("should show loading state before the first PDF exists", () => {
+ // what `usePDF()` returns before the provider has queued the first render
+ mockPdfStateRef.current = {
+ loading: false,
+ url: null,
+ error: null,
+ };
+
+ renderInvoicePDFDownloadLink();
+
+ const link = screen.getByRole("link", { name: LOADING_BUTTON_TEXT });
+
+ expect(link).toHaveClass("pointer-events-none");
+ expect(link).not.toHaveAttribute("download");
+ });
+
it("should set href and download attributes when PDF url is available", () => {
const invoiceData = {
...getInitialInvoiceData(),
@@ -294,11 +310,11 @@ describe("InvoicePDFDownloadLink", () => {
expect(showCTAToast).toHaveBeenCalledTimes(1);
});
- it("should show error toast when url is missing on click", async () => {
+ it("should show error toast when the PDF failed to generate and there is no url", async () => {
mockPdfStateRef.current = {
loading: false,
url: null,
- error: null,
+ error: new Error("PDF generation failed"),
};
const user = userEvent.setup();
@@ -313,7 +329,11 @@ describe("InvoicePDFDownloadLink", () => {
id: "file-not-available-error-toast",
}),
);
- expect(umamiTrackEvent).not.toHaveBeenCalled();
+ // the provider reports the failed render itself; the click must not count a download
+ expect(umamiTrackEvent).not.toHaveBeenCalledWith(
+ "download_invoice",
+ expect.anything(),
+ );
});
it("should block download inside in-app browser", async () => {
diff --git a/src/app/(main)/(app)/components/home-seo-content.tsx b/src/app/(main)/(app)/components/home-seo-content.tsx
new file mode 100644
index 0000000..238a01f
--- /dev/null
+++ b/src/app/(main)/(app)/components/home-seo-content.tsx
@@ -0,0 +1,221 @@
+import Link from "next/link";
+
+import {
+ SUPPORTED_CURRENCIES,
+ SUPPORTED_DATE_FORMATS,
+ SUPPORTED_INVOICE_PDF_LANGUAGES,
+} from "@/app/schema";
+import { FaqAccordion, FaqAccordionItem } from "@/components/ui/faq-accordion";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
+/**
+ * Plain, server-rendered copy below the invoice editor on `/`.
+ *
+ * The editor renders on the client, so before this the prerendered HTML held a loading
+ * skeleton and the footer: under 300 words for the page that gets most of the site's
+ * impressions. This says what the tool is in crawlable text, and links each landing page
+ * with anchor text that names it, which a footer link list does less convincingly.
+ *
+ * Only on `/`: `/stripe-template` is indexed as its own page and has its own copy,
+ * `StripeTemplateSeoContent`, written for the Stripe template's queries.
+ */
+export function HomeSeoContent() {
+ return (
+ <section
+ className="w-full bg-gray-100 px-4 pb-12 pt-8 md:pb-16"
+ aria-labelledby="home-seo-content-heading"
+ data-testid="home-seo-content"
+ >
+ <div className="mx-auto max-w-3xl space-y-10 text-slate-800">
+ <div>
+ <h2
+ id="home-seo-content-heading"
+ className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl"
+ >
+ A free invoice generator that runs in your browser
+ </h2>
+ <p className="mt-4 text-pretty text-lg leading-relaxed">
+ EasyInvoicePDF turns a short form into a PDF invoice. Type your
+ details, your client&apos;s and the line items, and the preview
+ redraws as you go. Download the PDF when it looks right. There is{" "}
+ <Link
+ href="/invoice-generator-no-login"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ no login and no signup
+ </Link>
+ , and the invoice is built on your own machine, so nothing you type
+ is uploaded.
+ </p>
+ <p className="mt-4 text-pretty text-lg leading-relaxed">
+ It is free, has no ads, and the{" "}
+ <Link
+ href="/open-source-invoice-generator"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ source code is open
+ </Link>{" "}
+ under AGPL-3.0, so you can read it or host your own copy.
+ </p>
+ </div>
+
+ <div>
+ <h2 className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ How to create an invoice
+ </h2>
+ <ol className="mt-4 list-decimal space-y-2 pl-6 text-base">
+ {HOW_TO_STEPS.map((step) => {
+ return (
+ <li key={step} className="text-pretty">
+ {step}
+ </li>
+ );
+ })}
+ </ol>
+ </div>
+
+ <div>
+ <h2 className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ What goes on the invoice
+ </h2>
+ <ul className="mt-4 list-disc space-y-2 pl-6 text-base">
+ <li className="text-pretty">
+ Labels in{" "}
+ <Link
+ href="/multi-language-invoice-generator"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ {SUPPORTED_INVOICE_PDF_LANGUAGES.length} languages
+ </Link>
+ , including the total written out in words
+ </li>
+ <li className="text-pretty">
+ {SUPPORTED_CURRENCIES.length} currencies, each with its own symbol
+ and number format
+ </li>
+ <li className="text-pretty">
+ {SUPPORTED_DATE_FORMATS.length} date formats, from 2026-03-20 to
+ March 20, 2026
+ </li>
+ <li className="text-pretty">
+ Your own tax label, such as VAT, GST or Sales Tax, or no tax
+ columns at all
+ </li>
+ <li className="text-pretty">
+ Your logo, bank details, and a QR code for a payment link
+ </li>
+ <li className="text-pretty">
+ Two layouts: a classic one and a{" "}
+ {/* a full page load, like the footer's link: the app keeps the template it
+ was opened on during client-side navigation */}
+ <a
+ href={STRIPE_TEMPLATE_PATHNAME}
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ Stripe-style invoice template
+ </a>
+ </li>
+ </ul>
+ <p className="mt-4 text-pretty text-base leading-relaxed">
+ Your details stay saved in your browser, so the next invoice starts
+ filled in. To send it, download the PDF or share a link that opens
+ the same invoice.
+ </p>
+ </div>
+
+ <div>
+ <h2 className="mb-3 text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ FAQ
+ </h2>
+ <FaqAccordion>
+ {FAQ.map((item) => {
+ return (
+ <FaqAccordionItem key={item.question} question={item.question}>
+ {item.answer}
+ </FaqAccordionItem>
+ );
+ })}
+ </FaqAccordion>
+ </div>
+
+ <div>
+ <h2 className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ Invoices for every kind of work
+ </h2>
+ <ul className="mt-4 grid grid-cols-1 gap-x-6 gap-y-2 text-base sm:grid-cols-2">
+ {USE_CASE_LINKS.map(({ href, label }) => {
+ return (
+ <li key={href}>
+ <Link
+ href={href}
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ {label}
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ </div>
+ </section>
+ );
+}
+
+const HOW_TO_STEPS = [
+ "Fill in your details as the seller, and your client's as the buyer",
+ "Pick the invoice language, currency and date format",
+ "Add a line for each product or service, with quantity and price",
+ "Download the PDF, or copy a link to send your client",
+] as const;
+
+const USE_CASE_LINKS = [
+ { href: "/freelance-invoice-template", label: "Freelance invoice template" },
+ {
+ href: "/contractor-invoice-template",
+ label: "Contractor invoice template",
+ },
+ { href: "/proforma-invoice-generator", label: "Proforma invoice generator" },
+ {
+ href: "/export-invoice-format",
+ label: "Export invoice format for services",
+ },
+ { href: "/invoice-template-pdf", label: "Invoice template PDF" },
+ {
+ href: "/stripe-invoice-alternative",
+ label: "Stripe-style invoice without Stripe",
+ },
+ { href: "/swedish-invoice-generator", label: "Swedish invoice generator" },
+ {
+ href: "/norwegian-invoice-generator",
+ label: "Norwegian invoice generator",
+ },
+] as const;
+
+const FAQ = [
+ {
+ question: "Is EasyInvoicePDF really free?",
+ answer:
+ "Yes. There is no paid plan, no watermark and no limit on how many invoices you make.",
+ },
+ {
+ question: "Do I need an account?",
+ answer:
+ "No. There is no signup and no email step. Open the page and start typing.",
+ },
+ {
+ question: "Where is my invoice data stored?",
+ answer:
+ "In your own browser's storage. The PDF is generated on your device, so the invoice never reaches a server. Clearing your browser data removes it, so keep the PDFs you need.",
+ },
+ {
+ question: "Can I add my logo?",
+ answer:
+ "Yes. Both templates accept a JPEG, PNG or WebP logo at the top of the invoice.",
+ },
+ {
+ question: "Is this accounting software?",
+ answer:
+ "No. It makes invoice PDFs and does not track payments, file taxes or keep books. Check the invoice against the rules that apply to your business.",
+ },
+] as const;
diff --git a/src/app/(main)/(app)/components/index.tsx b/src/app/(main)/(app)/components/index.tsx
index f88da5f..65ce465 100644
--- a/src/app/(main)/(app)/components/index.tsx
+++ b/src/app/(main)/(app)/components/index.tsx
@@ -152,6 +152,7 @@ export function InvoiceClientPage({
isMobile,
canShareInvoice,
currentInvoiceFormDataRef,
+ isUnmodifiedInvoiceFromLink,
mobileDockNotice,
onMobileTabChange,
}: {
@@ -161,6 +162,11 @@ export function InvoiceClientPage({
isMobile: boolean;
canShareInvoice: boolean;
currentInvoiceFormDataRef: RefObject<(() => InvoiceData | null) | null>;
+ /**
+ * The invoice is still the one opened from a shared link. "Invoice last updated" is
+ * hidden then: it comes from this browser's metadata and says nothing about that invoice.
+ */
+ isUnmodifiedInvoiceFromLink: boolean;
/**
* Rendered inside the mobile dock, which it positions itself against to float just above
* it -- the welcome popup on phones. Ignored on desktop, where the popup floats instead.
@@ -171,11 +177,12 @@ export function InvoiceClientPage({
}) {
const appMetadata = useAppMetadata();
- const invoiceLastUpdatedAtFormatted = appMetadata?.invoiceLastUpdatedAt
- ? dayjs(appMetadata.invoiceLastUpdatedAt)
- .locale("en")
- .format("MMM D, YYYY [at] HH:mm")
- : null;
+ const invoiceLastUpdatedAtFormatted =
+ appMetadata?.invoiceLastUpdatedAt && !isUnmodifiedInvoiceFromLink
+ ? dayjs(appMetadata.invoiceLastUpdatedAt)
+ .locale("en")
+ .format("MMM D, YYYY [at] HH:mm")
+ : null;
const defaultMobileTab =
appMetadata?.lastVisitedMobileTab || DEFAULT_MOBILE_TAB;
diff --git a/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx
index 1fbb8dc..f80e996 100644
--- a/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx
+++ b/src/app/(main)/(app)/components/invoice-form/sections/components/import-contacts-dialog.tsx
@@ -1,4 +1,4 @@
-import { Check, ChevronDown, FileUp, FileWarning } from "lucide-react";
+import { ChevronDown, FileUp, FileWarning } from "lucide-react";
import { useEffect, useEffectEvent, useState } from "react";
import {
@@ -226,17 +226,9 @@ function ChooseFileStep({
</span>
</FilePickerLabel>
- <ul className="space-y-1.5 text-sm text-slate-600">
+ <ul className="list-disc space-y-1.5 pl-5 text-sm text-slate-600">
{IMPORT_RULES.map((rule) => {
- return (
- <li key={rule} className="flex gap-2">
- <Check
- className="mt-0.5 size-3.5 shrink-0 text-green-600"
- aria-hidden
- />
- {rule}
- </li>
- );
+ return <li key={rule}>{rule}</li>;
})}
</ul>
@@ -594,7 +586,7 @@ interface ContactNameProps {
/** Wraps rather than truncates, so a long name can be read in full. */
function ContactName({ name }: ContactNameProps) {
- return <p className="text-pretty break-words">{name}</p>;
+ return <p className="text-pretty break-words pb-0.5">{name}</p>;
}
interface ContactAddressProps {
diff --git a/src/app/(main)/(app)/components/invoice-page-header.tsx b/src/app/(main)/(app)/components/invoice-page-header.tsx
index f30d2a2..ae74653 100644
--- a/src/app/(main)/(app)/components/invoice-page-header.tsx
+++ b/src/app/(main)/(app)/components/invoice-page-header.tsx
@@ -4,6 +4,7 @@ import { LinkIcon } from "lucide-react";
import { useState } from "react";
import { ProjectLogoDescription } from "@/app/(components)/project-logo-description";
+import { APP_PAGE_HEADING } from "@/app/(main)/(app)/app-page-heading";
import { HowItWorksVideoDialog } from "@/app/(main)/(app)/components/how-it-works-video-dialog";
import { InvoicePDFDownloadLink } from "@/app/(main)/(app)/components/invoice-pdf-download-link";
import { ShareInvoiceButton } from "@/app/(main)/(app)/components/share-invoice-button";
@@ -48,15 +49,10 @@ export function InvoicePageHeader({
<div className="flex items-center">
<ProjectLogo className="h-8 w-8" />
<ProjectLogoDescription
- title={
- <h1 className="text-balance text-xl font-bold text-slate-800 lg:text-2xl">
- EasyInvoicePDF
- </h1>
- }
description={
- <h2 className="text-balance text-[12px] text-slate-700 sm:text-[13px]">
- Free & Open-Source Invoice Generator
- </h2>
+ <h1 className="text-balance text-[12px] text-slate-700 sm:text-[13px]">
+ {APP_PAGE_HEADING[invoiceDataState.template]}
+ </h1>
}
/>
</div>
diff --git a/src/app/(main)/(app)/components/invoice-pdf-download-link.tsx b/src/app/(main)/(app)/components/invoice-pdf-download-link.tsx
index 5827438..3139765 100644
--- a/src/app/(main)/(app)/components/invoice-pdf-download-link.tsx
+++ b/src/app/(main)/(app)/components/invoice-pdf-download-link.tsx
@@ -185,6 +185,12 @@ export function InvoicePDFDownloadLink({
return;
}, [pdfLoading]);
+ // `usePDF()` starts out as `{ url: null, loading: false }`, before the provider has queued
+ // the first render. Without counting that as loading the button read "Download PDF" with
+ // no file behind it (`href="#"`), and a click in that window only got the "File not
+ // available" toast. A failed render (`error`) is not loading: there the toast is right.
+ const isPreparingPdf = isLoading || (!url && !error);
+
// The button is a fixed width so the layout does not shift while the PDF regenerates,
// which means "Download PDF in <language>" has to be measured against the longest name.
const isLongLanguageString =
@@ -219,14 +225,14 @@ export function InvoicePDFDownloadLink({
"focus-visible:border-indigo-500 focus-visible:ring focus-visible:ring-indigo-200 focus-visible:ring-opacity-50",
"dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-50/90 lg:mb-0 lg:w-[230px]",
{
- "pointer-events-none opacity-70": isLoading,
+ "pointer-events-none opacity-70": isPreparingPdf,
"lg:w-[250px]": isLongLanguageString,
"lg:w-[275px]": isExtraLongLanguageString,
},
)}
>
<ButtonContent
- isLoading={isLoading}
+ isLoading={isPreparingPdf}
isMobile={isMobile}
language={invoiceData.language}
/>
diff --git a/src/app/(main)/(app)/components/stripe-template-seo-content.tsx b/src/app/(main)/(app)/components/stripe-template-seo-content.tsx
new file mode 100644
index 0000000..a0ddcf8
--- /dev/null
+++ b/src/app/(main)/(app)/components/stripe-template-seo-content.tsx
@@ -0,0 +1,166 @@
+import Link from "next/link";
+
+import { SUPPORTED_INVOICE_PDF_LANGUAGES } from "@/app/schema";
+import { FaqAccordion, FaqAccordionItem } from "@/components/ui/faq-accordion";
+
+import { StripeTemplateSwitchSentence } from "./stripe-template-switch-sentence";
+
+/**
+ * Plain, server-rendered copy below the invoice editor on `/stripe-template`.
+ *
+ * The route has its own canonical URL and title ("Stripe Invoice Template"), so it is
+ * indexed as a page of its own, but the editor renders on the client: without this, its
+ * prerendered HTML is a loading skeleton and the footer. `HomeSeoContent` solves the same
+ * problem on `/`.
+ *
+ * Written for "Stripe invoice template": what the layout looks like and how to fill it
+ * in. The general pitch (free, no login, open source) is `/`'s, and "Stripe invoice
+ * generator" belongs to `/stripe-invoice-alternative`, so this links to both rather than
+ * repeating them.
+ */
+export function StripeTemplateSeoContent() {
+ return (
+ <section
+ className="w-full bg-gray-100 px-4 pb-12 pt-8 md:pb-16"
+ aria-labelledby="stripe-template-seo-content-heading"
+ data-testid="stripe-template-seo-content"
+ >
+ <div className="mx-auto max-w-3xl space-y-10 text-slate-800">
+ <div>
+ <h2
+ id="stripe-template-seo-content-heading"
+ className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl"
+ >
+ A free Stripe-style invoice template
+ </h2>
+ <p className="mt-4 text-pretty text-lg leading-relaxed">
+ The Stripe invoice template follows the layout of the invoices
+ Stripe sends. The amount due and its due date sit in bold above a
+ single table of line items, with a short summary of totals below.
+ Fill in the form and the preview redraws as you type, then download
+ the PDF.
+ </p>
+ <p className="mt-4 text-pretty text-lg leading-relaxed">
+ You don&apos;t need a Stripe account. It is a layout you fill in,
+ not a payments service: no products to set up and no dashboard. The
+ invoice is built in your browser, and{" "}
+ <Link
+ href="/invoice-generator-no-login"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ there is no signup
+ </Link>
+ .
+ </p>
+ </div>
+
+ <div>
+ <h2 className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ What&apos;s on the template
+ </h2>
+ <ul className="mt-4 list-disc space-y-2 pl-6 text-base">
+ {TEMPLATE_PARTS.map((part) => {
+ return (
+ <li key={part} className="text-pretty">
+ {part}
+ </li>
+ );
+ })}
+ <li className="text-pretty">
+ Labels in{" "}
+ <Link
+ href="/multi-language-invoice-generator"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ {SUPPORTED_INVOICE_PDF_LANGUAGES.length} languages
+ </Link>
+ , with your own tax label such as VAT, GST or Sales Tax
+ </li>
+ </ul>
+ </div>
+
+ <div>
+ <h2 className="text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ How to fill in the Stripe invoice template
+ </h2>
+ <ol className="mt-4 list-decimal space-y-2 pl-6 text-base">
+ {HOW_TO_STEPS.map((step) => {
+ return (
+ <li key={step} className="text-pretty">
+ {step}
+ </li>
+ );
+ })}
+ </ol>
+ <StripeTemplateSwitchSentence />
+ </div>
+
+ <div>
+ <h2 className="mb-3 text-balance text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl">
+ FAQ
+ </h2>
+ <FaqAccordion>
+ {FAQ.map((item) => {
+ return (
+ <FaqAccordionItem key={item.question} question={item.question}>
+ {item.answer}
+ </FaqAccordionItem>
+ );
+ })}
+ </FaqAccordion>
+ <p className="mt-6 text-pretty text-base leading-relaxed">
+ Comparing it with billing through Stripe itself? See the{" "}
+ <Link
+ href="/stripe-invoice-alternative"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ Stripe invoice generator
+ </Link>{" "}
+ page.
+ </p>
+ </div>
+ </div>
+ </section>
+ );
+}
+
+const TEMPLATE_PARTS = [
+ "The amount due and the due date in bold, above the line items",
+ "An optional Pay online link under the amount, pointing to any payment page you use",
+ "A line-item table with quantity and unit price, then subtotal, tax and total",
+ "Your logo beside the invoice title, and your details next to your client's",
+ "A footer on every page with the invoice number, the amount due and page numbers",
+ "An optional QR code with any text you choose, such as a payment link",
+ "US Letter page size",
+] as const;
+
+const HOW_TO_STEPS = [
+ "Add your details as the seller and your client's as the buyer",
+ "Set the invoice number, issue date and due date",
+ "Add a line for each product or service, with quantity and price",
+ "Paste a payment link into Pay online if you want one on the invoice",
+ "Download the PDF, or copy a link that opens the same invoice",
+] as const;
+
+const FAQ = [
+ {
+ question: "Do I need a Stripe account to use this template?",
+ answer:
+ "No. The template copies the look of a Stripe invoice, but nothing here connects to Stripe. You type the details and download a PDF.",
+ },
+ {
+ question: "Can my client pay from the invoice?",
+ answer:
+ "Only through a link you add. Paste any payment URL, such as a Stripe Payment Link, PayPal or your bank's page, into Pay online and it becomes a clickable link in the PDF. You can put the same link in the QR code field too.",
+ },
+ {
+ question: "Is the Stripe invoice template free?",
+ answer:
+ "Yes. There is no paid plan, no watermark and no limit on how many invoices you download.",
+ },
+ {
+ question: "Can I add my logo?",
+ answer:
+ "Yes. Upload a JPEG, PNG or WebP and it appears at the top of the invoice.",
+ },
+] as const;
diff --git a/src/app/(main)/(app)/components/stripe-template-switch-sentence.tsx b/src/app/(main)/(app)/components/stripe-template-switch-sentence.tsx
new file mode 100644
index 0000000..051a33b
--- /dev/null
+++ b/src/app/(main)/(app)/components/stripe-template-switch-sentence.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { usePathname } from "next/navigation";
+
+import {
+ getRouteTemplate,
+ STRIPE_TEMPLATE_PATHNAME,
+} from "@/utils/invoice-app-url";
+
+/**
+ * The "switch template" sentence in `StripeTemplateSeoContent`, the one line of that block
+ * that depends on the template in use.
+ *
+ * A template switch rewrites the address bar with `history.replaceState` and leaves the
+ * server-rendered copy alone, so after switching to the classic template a static "switch
+ * to the classic template" would offer the template already open. `usePathname()` follows
+ * those rewrites. The prerender sees `/stripe-template`, so the served HTML -- what a
+ * crawler reads -- always has the classic-template link.
+ *
+ * Both links are full page loads: the app keeps the template it was opened on during
+ * client-side navigation.
+ */
+export function StripeTemplateSwitchSentence() {
+ const pathname = usePathname();
+
+ return getRouteTemplate(pathname) === "stripe" ? (
+ <p className="mt-4 text-pretty text-base leading-relaxed">
+ Prefer a plainer A4 layout? Switch to the{" "}
+ {/* an explicit template: a bare `/` sends a visitor whose saved invoice uses this
+ template straight back here */}
+ {/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
+ <a
+ href="/?template=default"
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ classic invoice template
+ </a>
+ . Your details carry over.
+ </p>
+ ) : (
+ <p className="mt-4 text-pretty text-base leading-relaxed">
+ Want the Stripe layout back? Switch to the{" "}
+ <a
+ href={STRIPE_TEMPLATE_PATHNAME}
+ className="font-medium text-slate-900 underline underline-offset-4"
+ >
+ Stripe invoice template
+ </a>
+ . Your details carry over.
+ </p>
+ );
+}
diff --git a/src/app/(main)/(app)/home-json-ld.tsx b/src/app/(main)/(app)/home-json-ld.tsx
index 53768d8..758f1a1 100644
--- a/src/app/(main)/(app)/home-json-ld.tsx
+++ b/src/app/(main)/(app)/home-json-ld.tsx
@@ -1,7 +1,7 @@
import type { Graph } from "schema-dts";
import { PROD_WEBSITE_URL } from "@/config";
-import { JSON_LD_IDS } from "@/lib/seo/json-ld-ids";
+import { JSON_LD_IDS, pageWebPageId } from "@/lib/seo/json-ld-ids";
import { JsonLdScript } from "@/lib/seo/render-json-ld";
import {
buildFullWebSite,
@@ -9,12 +9,35 @@ import {
buildSiteNavigationList,
buildWebApplication,
HOME_PAGE_DESCRIPTION,
- SITE_NAME,
+ HOME_PAGE_TITLE,
} from "@/lib/seo/site-entities";
-export function buildHomeJsonLdGraph(): Graph {
- const pageUrl = `${PROD_WEBSITE_URL}/`;
+/** The page a `WebPage` node describes: the invoice app at one of its routes. */
+export interface InvoiceAppWebPage {
+ /** Absolute production URL of the route, e.g. `https://easyinvoicepdf.com/`. */
+ url: string;
+ name: string;
+ /** The route's meta description. */
+ description: string;
+}
+
+/** The home page, `/`: the invoice app on the default template. */
+export const HOME_WEB_PAGE = {
+ url: `${PROD_WEBSITE_URL}/`,
+ name: HOME_PAGE_TITLE,
+ description: HOME_PAGE_DESCRIPTION,
+} as const satisfies InvoiceAppWebPage;
+/**
+ * Builds the JSON-LD graph of an invoice app route: the site-wide entities plus a
+ * `WebPage` for the route itself, so `/` and `/stripe-template` each describe their own URL.
+ *
+ * @param webPage - The route the graph is rendered on. Defaults to the home page.
+ * @returns The schema.org graph.
+ */
+export function buildHomeJsonLdGraph(
+ webPage: InvoiceAppWebPage = HOME_WEB_PAGE,
+): Graph {
return {
"@context": "https://schema.org",
"@graph": [
@@ -24,10 +47,10 @@ export function buildHomeJsonLdGraph(): Graph {
buildSiteNavigationList(),
{
"@type": "WebPage",
- "@id": `${pageUrl}#webpage`,
- url: pageUrl,
- name: SITE_NAME,
- description: HOME_PAGE_DESCRIPTION,
+ "@id": pageWebPageId(webPage.url),
+ url: webPage.url,
+ name: webPage.name,
+ description: webPage.description,
inLanguage: "en",
isPartOf: {
"@id": JSON_LD_IDS.website,
@@ -43,6 +66,13 @@ export function buildHomeJsonLdGraph(): Graph {
};
}
-export function HomeJsonLd() {
- return <JsonLdScript id="json-ld-home" data={buildHomeJsonLdGraph()} />;
+export function HomeJsonLd({
+ webPage = HOME_WEB_PAGE,
+}: {
+ /** The route this is rendered on. Defaults to the home page. */
+ webPage?: InvoiceAppWebPage;
+}) {
+ return (
+ <JsonLdScript id="json-ld-home" data={buildHomeJsonLdGraph(webPage)} />
+ );
}
diff --git a/src/app/(main)/(app)/hooks/__tests__/use-in-app-browser-notice.test.tsx b/src/app/(main)/(app)/hooks/__tests__/use-in-app-browser-notice.test.tsx
index bd5f7b6..95426b4 100644
--- a/src/app/(main)/(app)/hooks/__tests__/use-in-app-browser-notice.test.tsx
+++ b/src/app/(main)/(app)/hooks/__tests__/use-in-app-browser-notice.test.tsx
@@ -4,7 +4,7 @@ import { renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DeviceContextProvider } from "@/contexts/device-context";
-import type { InAppInfo } from "@/lib/check-device.server";
+import type { InAppInfo } from "@/lib/detect-device";
import { isTelegramInAppBrowser } from "@/utils/is-telegram-in-app-browser";
import { useInAppBrowserNotice } from "../use-in-app-browser-notice";
diff --git a/src/app/(main)/(app)/invoice-app-page.tsx b/src/app/(main)/(app)/invoice-app-page.tsx
new file mode 100644
index 0000000..81e4438
--- /dev/null
+++ b/src/app/(main)/(app)/invoice-app-page.tsx
@@ -0,0 +1,211 @@
+import * as Sentry from "@sentry/nextjs";
+import type { Metadata } from "next";
+import { type ReactNode, Suspense } from "react";
+
+import { fetchGithubStars } from "@/actions/fetch-github-stars";
+import { Footer } from "@/app/(components)/footer";
+import { getLatestChangelogSummary } from "@/app/(main)/changelog/utils";
+import type { SupportedTemplates } from "@/app/schema";
+import {
+ APP_URL,
+ PROD_WEBSITE_URL,
+ STATIC_ASSETS_URL,
+ TWITTER_CREATOR,
+} from "@/config";
+import { getIsIndexableEnvironment } from "@/lib/seo/indexing-utils";
+import {
+ HOME_PAGE_DESCRIPTION,
+ HOME_PAGE_TITLE,
+} from "@/lib/seo/site-entities";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
+import { APP_PAGE_TITLE } from "./app-page-heading";
+import { HomeSeoContent } from "./components/home-seo-content";
+import { StripeTemplateSeoContent } from "./components/stripe-template-seo-content";
+import { CTAToastProvider } from "./contexts/cta-toast-context";
+import {
+ HOME_WEB_PAGE,
+ HomeJsonLd,
+ type InvoiceAppWebPage,
+} from "./home-json-ld";
+import { InvoicePageLoadingSkeleton } from "./loading";
+import { AppPageClient } from "./page.client";
+
+/**
+ * The invoice generator, shared by `/` (default template) and `/stripe-template`.
+ *
+ * Deliberately free of request-bound APIs (`searchParams`, `headers()`, `cookies()`), so
+ * both routes are prerendered and revalidated in the background (every 4 hours, the
+ * `fetchGithubStars` revalidate) instead of rendered per request. Everything that depends
+ * on the URL -- the template, a shared `?data=` invoice -- is read on the client.
+ */
+export async function InvoiceAppPage({
+ template,
+}: {
+ /** The template the route opens with. */
+ template: SupportedTemplates;
+}) {
+ const isIndexableEnvironment = getIsIndexableEnvironment();
+
+ const [githubStarsCount, latestChangelog] = await Promise.all([
+ fetchGithubStars(),
+ getLatestChangelogSummary().catch((error) => {
+ // don't fail the page if we can't load the latest changelog summary
+ console.error("[AppPage] Failed to load latest changelog summary", error);
+
+ Sentry.captureException(
+ new Error(
+ `[AppPage] Failed to load latest changelog summary: ${error}`,
+ ),
+ );
+
+ return null;
+ }),
+ ]);
+
+ return (
+ <CTAToastProvider>
+ {isIndexableEnvironment ? (
+ <HomeJsonLd webPage={TEMPLATE_WEB_PAGE[template]} />
+ ) : null}
+ {/* `AppPageClient` reads `useSearchParams()`, which a prerendered page can only
+ resolve in the browser: the prerender falls back to the nearest Suspense boundary
+ and renders the rest on the client. Without a boundary of its own that was
+ `loading.tsx`, above everything here -- the JSON-LD was left out of the static
+ HTML. The editor is client-only anyway (the invoice lives in localStorage or
+ `?data=`), and the fallback is the skeleton `loading.tsx` renders. */}
+ <Suspense fallback={<InvoicePageLoadingSkeleton template={template} />}>
+ <AppPageClient
+ githubStarsCount={githubStarsCount}
+ latestChangelog={latestChangelog}
+ />
+ </Suspense>
+ {TEMPLATE_SEO_CONTENT[template]}
+ <Footer />
+ </CTAToastProvider>
+ );
+}
+
+/**
+ * Builds the metadata of the invoice app route for a template: title, canonical URL,
+ * OpenGraph/Twitter cards and robots directives.
+ *
+ * @param template - The template the route opens with.
+ * @returns Static Next.js metadata for the route.
+ */
+export function buildInvoiceAppMetadata(
+ template: SupportedTemplates,
+): Metadata {
+ const { title, description, canonical, images } = TEMPLATE_META[template];
+
+ return {
+ title,
+ description,
+ robots: resolveAppPageRobots(getIsIndexableEnvironment()),
+ alternates: {
+ canonical,
+ types: {
+ "text/markdown": `${APP_URL}/invoice-generator.md`,
+ },
+ },
+ openGraph: {
+ title,
+ description,
+ siteName: "EasyInvoicePDF.com | Free Invoice PDF Generator",
+ locale: "en_US",
+ type: "website",
+ url: canonical,
+ images: [...images],
+ },
+ twitter: {
+ card: "summary_large_image",
+ title,
+ description,
+ creator: TWITTER_CREATOR,
+ images: [...images],
+ },
+ };
+}
+
+/**
+ * Resolves `robots` metadata for the invoice app routes.
+ *
+ * Indexing is allowed only on an indexable environment (production deploy). Preview
+ * builds use strict `noindex,nofollow`. Shared `?data=` links are handled outside the
+ * prerendered metadata, see `getIsIndexableEnvironment`.
+ *
+ * @param isIndexableEnvironment - Whether this deployment may be indexed.
+ * @returns Next.js `Metadata.robots` object for this page.
+ */
+function resolveAppPageRobots(
+ isIndexableEnvironment: boolean,
+): NonNullable<Metadata["robots"]> {
+ return {
+ index: isIndexableEnvironment,
+ follow: isIndexableEnvironment,
+ googleBot: {
+ index: isIndexableEnvironment,
+ follow: isIndexableEnvironment,
+ },
+ };
+}
+
+const TEMPLATE_META = {
+ default: {
+ title: HOME_PAGE_TITLE,
+ description: HOME_PAGE_DESCRIPTION,
+ canonical: `${APP_URL}/`, // we use root URL as canonical for SEO purposes
+ images: [
+ {
+ url: `${STATIC_ASSETS_URL}/easy-invoice-opengraph-image.png?v=1755773879597`,
+ type: "image/png",
+ width: 1200,
+ height: 630,
+ alt: "Default Invoice Template - EasyInvoicePDF.com",
+ },
+ ],
+ },
+ stripe: {
+ title: APP_PAGE_TITLE.stripe,
+ // its own wording, so the route does not share `/`'s description
+ description:
+ "Free Stripe invoice template. Fill in a Stripe-style invoice, add your logo and a Pay online link, and download the PDF. No Stripe account, no signup.",
+ canonical: `${APP_URL}${STRIPE_TEMPLATE_PATHNAME}`, // its own route, so the Stripe template is indexed as its own page
+ images: [
+ {
+ url: `${STATIC_ASSETS_URL}/stripe-og.png?v=1755773921680`,
+ type: "image/png",
+ width: 1200,
+ height: 630,
+ alt: "Stripe Invoice Template - EasyInvoicePDF.com",
+ },
+ ],
+ },
+} as const satisfies Record<
+ SupportedTemplates,
+ {
+ title: string;
+ description: string;
+ canonical: string;
+ images: NonNullable<Metadata["openGraph"]>["images"];
+ }
+>;
+
+/**
+ * The crawlable copy below the editor on each template's route. Each says something
+ * different, so the two routes don't compete for the same queries.
+ */
+const TEMPLATE_SEO_CONTENT = {
+ default: <HomeSeoContent />,
+ stripe: <StripeTemplateSeoContent />,
+} as const satisfies Record<SupportedTemplates, ReactNode>;
+
+/** The `WebPage` JSON-LD node of each template's route. */
+const TEMPLATE_WEB_PAGE = {
+ default: HOME_WEB_PAGE,
+ stripe: {
+ url: `${PROD_WEBSITE_URL}${STRIPE_TEMPLATE_PATHNAME}`,
+ name: TEMPLATE_META.stripe.title,
+ description: TEMPLATE_META.stripe.description,
+ },
+} as const satisfies Record<SupportedTemplates, InvoiceAppWebPage>;
diff --git a/src/app/(main)/(app)/layout.tsx b/src/app/(main)/(app)/layout.tsx
index 479997f..3d6588f 100644
--- a/src/app/(main)/(app)/layout.tsx
+++ b/src/app/(main)/(app)/layout.tsx
@@ -1,33 +1,16 @@
-import { DeviceContextProvider } from "@/contexts/device-context";
-import { checkDeviceUserAgent } from "@/lib/check-device.server";
+import { UserAgentDeviceContextProvider } from "@/contexts/device-context";
/**
- * Layout of the invoice generator itself (`/`).
+ * Layout of the invoice generator itself (`/` and `/stripe-template`).
*
- * Server-side device detection lives here rather than in the shared root document
- * (`src/app/(components)/root-document.tsx`): `checkDeviceUserAgent()` reads
- * `headers()`, and from the root that made *every* route request-bound — which is
- * why the marketing pages all needed `export const dynamic = "force-static"` to stay
- * prerendered. `useDeviceContext()` is only consumed under this route group, and `/`
- * is rendered per request anyway (`page.tsx` reads `searchParams`), so nothing is
- * lost by scoping the header read to it.
+ * Device detection runs in the browser (`UserAgentDeviceContextProvider`), not from the
+ * request headers: reading `headers()` here made both routes render per request, and
+ * they have nothing else that needs the request -- the invoice lives in `localStorage`
+ * or `?data=`, both read on the client. Keeping this layout free of dynamic APIs is what
+ * lets the app be prerendered and served from the CDN.
*/
-export default async function AppLayout({ children }: LayoutProps<"/">) {
- const {
- isDesktop: isDesktopServer,
- isAndroid,
- isMobile,
- inAppInfo,
- } = await checkDeviceUserAgent();
-
+export default function AppLayout({ children }: LayoutProps<"/">) {
return (
- <DeviceContextProvider
- isDesktop={isDesktopServer}
- isAndroid={isAndroid}
- isMobile={isMobile}
- inAppInfo={inAppInfo}
- >
- {children}
- </DeviceContextProvider>
+ <UserAgentDeviceContextProvider>{children}</UserAgentDeviceContextProvider>
);
}
diff --git a/src/app/(main)/(app)/loading.tsx b/src/app/(main)/(app)/loading.tsx
index c78aa91..f364377 100644
--- a/src/app/(main)/(app)/loading.tsx
+++ b/src/app/(main)/(app)/loading.tsx
@@ -1,39 +1,64 @@
import { Footer } from "@/app/(components)/footer";
import { ProjectLogoDescription } from "@/app/(components)/project-logo-description";
+import { APP_PAGE_HEADING } from "@/app/(main)/(app)/app-page-heading";
+import type { SupportedTemplates } from "@/app/schema";
import { ProjectLogo } from "@/components/etc/project-logo";
import { Skeleton } from "@/components/ui/skeleton";
+/**
+ * The route-level skeleton, shown on navigation to `/` or `/stripe-template`.
+ *
+ * It is in the prerendered HTML alongside the page's own fallback, and it cannot tell the
+ * two routes apart, so it renders the tagline without a heading: the h1 comes from the
+ * page's fallback (see `InvoiceAppPage`), which knows its template.
+ */
export default function Loading() {
- return <InvoicePageLoadingSkeleton />;
+ return (
+ <>
+ <InvoicePageLoadingSkeleton />
+ <Footer />
+ </>
+ );
}
/**
* Displays the loading skeleton for the Invoice Page.
- * Shows placeholders for the header, invoice editor, and footer while content is being loaded.
+ * Shows placeholders for the header and invoice editor while content is being loaded.
+ *
+ * The footer is not part of it: on the page it is rendered on the server, below the editor
+ * (see `InvoiceAppPage`), so it is in the prerendered HTML whatever the editor is doing.
*/
-export function InvoicePageLoadingSkeleton() {
+export function InvoicePageLoadingSkeleton({
+ template,
+}: {
+ /**
+ * The template the route opens with. Picks the page's h1; without it the tagline is not
+ * a heading, see `Loading`.
+ */
+ template?: SupportedTemplates;
+}) {
return (
- <>
- <main
- className="flex flex-col items-center justify-start bg-gray-100 pb-4 sm:p-4 md:justify-center lg:min-h-screen"
- aria-busy="true"
- aria-label="Loading invoice editor"
- >
- <div className="w-full max-w-[62rem] bg-white p-3 shadow-lg sm:mb-0 sm:rounded-lg sm:p-6 sm:pb-1 min-[1400px]:max-w-7xl 2xl:max-w-[1480px]">
- <LoadingHeader />
+ <main
+ className="flex flex-col items-center justify-start bg-gray-100 pb-4 sm:p-4 md:justify-center lg:min-h-screen"
+ aria-busy="true"
+ aria-label="Loading invoice editor"
+ >
+ <div className="w-full max-w-[62rem] bg-white p-3 shadow-lg sm:mb-0 sm:rounded-lg sm:p-6 sm:pb-1 min-[1400px]:max-w-7xl 2xl:max-w-[1480px]">
+ <LoadingHeader template={template} />
- <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
- <MobileEditorLoading />
- <DesktopEditorLoading />
- </div>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
+ <MobileEditorLoading />
+ <DesktopEditorLoading />
</div>
- </main>
- <Footer />
- </>
+ </div>
+ </main>
);
}
-function LoadingHeader() {
+function LoadingHeader({ template }: { template?: SupportedTemplates }) {
+ const taglineClassName =
+ "text-balance text-[12px] text-slate-700 sm:text-[13px]";
+
return (
<div className="lg:mb-0 lg:h-auto">
<div className="flex w-full flex-row flex-wrap items-center justify-between lg:flex-nowrap">
@@ -42,9 +67,13 @@ function LoadingHeader() {
<ProjectLogo className="h-8 w-8" />
<ProjectLogoDescription
description={
- <h2 className="text-balance text-[12px] text-slate-700 sm:text-[13px]">
- Free &amp; Open-Source Invoice Generator
- </h2>
+ template ? (
+ <h1 className={taglineClassName}>
+ {APP_PAGE_HEADING[template]}
+ </h1>
+ ) : (
+ <p className={taglineClassName}>{APP_PAGE_HEADING.default}</p>
+ )
}
/>
</div>
diff --git a/src/app/(main)/(app)/page.client.tsx b/src/app/(main)/(app)/page.client.tsx
index abc0daa..f11bd7b 100644
--- a/src/app/(main)/(app)/page.client.tsx
+++ b/src/app/(main)/(app)/page.client.tsx
@@ -5,12 +5,11 @@ import {
compressToEncodedURIComponent,
decompressFromEncodedURIComponent,
} from "lz-string";
-import { useSearchParams } from "next/navigation";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { usePathname, useSearchParams } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { z } from "zod";
-import { Footer } from "@/app/(components)/footer";
+import { APP_PAGE_TITLE } from "@/app/(main)/(app)/app-page-heading";
import { InvoicePageHeader } from "@/app/(main)/(app)/components/invoice-page-header";
import { InvoicePdfInstanceProvider } from "@/app/(main)/(app)/contexts/invoice-pdf-instance-context";
import { InvoicePageLoadingSkeleton } from "@/app/(main)/(app)/loading";
@@ -24,7 +23,6 @@ import { getInitialInvoiceData } from "@/app/constants";
import {
invoiceSchema,
PDF_DATA_LOCAL_STORAGE_KEY,
- SUPPORTED_TEMPLATES,
type InvoiceData,
} from "@/app/schema";
import { GitHubStarCTA } from "@/components/github-star-cta";
@@ -34,6 +32,12 @@ import { useDeviceContext } from "@/contexts/device-context";
import { debugLog } from "@/lib/debug-log";
import { haptic } from "@/lib/haptic";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+import {
+ buildInvoiceAppUrl,
+ getRouteTemplate,
+ getTemplateFromUrl,
+ isUrlForTemplate,
+} from "@/utils/invoice-app-url";
import {
compressInvoiceData,
decompressInvoiceData,
@@ -53,25 +57,31 @@ import { selectInvoiceTemplate } from "./utils/select-invoice-template";
// import { InvoicePDFDownloadMultipleLanguages } from "./components/invoice-pdf-download-multiple-languages";
/**
- * Rewrites the query string of `/` in place.
+ * Rewrites the URL of the invoice app in place.
*
- * Every URL rewrite on this page is cosmetic -- keeping `?template=` in sync, adding or
- * dropping `?data=` -- and lands on the page that is already rendered. `router.replace`
- * treats each one as a navigation and refetches the RSC payload for `/`, so a plain page
- * load spent a whole extra server round trip just to append `?template=default`. Next's
- * router syncs with the native History API, so `useSearchParams()` still updates and
- * nothing is refetched.
+ * Every URL rewrite on this page is cosmetic -- keeping the template in sync (`/` vs
+ * `/stripe-template`), adding or dropping `?data=` -- and lands on the page
+ * that is already rendered. `router.replace` treats each one as a navigation and refetches
+ * the RSC payload (and, for a template switch, would remount the editor on the other
+ * route), so a plain page load spent a whole extra server round trip just to tidy up the
+ * URL. Next's router syncs with the native History API, so
+ * `usePathname()` and `useSearchParams()` still update and nothing is refetched.
+ *
+ * @param url - The root-relative URL to put in the address bar, see `buildInvoiceAppUrl`.
+ */
+function replaceUrl(url: string) {
+ window.history.replaceState(null, "", url);
+}
+
+/**
+ * Rewrites only the query string, keeping the current pathname (and so the template).
*
* @param params - The complete query string to put in the address bar.
*/
function replaceUrlQuery(params: URLSearchParams) {
const query = params.toString();
- window.history.replaceState(
- null,
- "",
- query ? `?${query}` : window.location.pathname,
- );
+ replaceUrl(query ? `?${query}` : window.location.pathname);
}
/**
@@ -96,22 +106,13 @@ export function AppPageClient({
latestChangelog: ChangelogSummary | null;
}) {
const searchParams = useSearchParams();
-
- const urlTemplateSearchParam = searchParams.get("template");
+ const pathname = usePathname();
/**
- * The `?template=` parameter, validated.
- *
- * Memoized so the parse happens once per URL rather than once per render, and so the result
- * keeps its identity -- `loadFromLocalStorage` below closes over it, and a fresh object every
- * render would make that callback (and everything keyed on it) unstable for no reason.
+ * The template the URL asks for: `/stripe-template`, or a legacy `?template=` on `/`.
+ * `null` on a bare `/`, which has no preference: the saved invoice's template is used.
*/
- const templateValidation = useMemo(() => {
- return z
- .enum(SUPPORTED_TEMPLATES)
- .default("default")
- .safeParse(urlTemplateSearchParam);
- }, [urlTemplateSearchParam]);
+ const urlTemplate = getTemplateFromUrl({ pathname, searchParams });
const { isDesktop, isUADesktop } = useDeviceContext();
const isMobile = !isDesktop;
@@ -142,6 +143,17 @@ export function AppPageClient({
const isViewingSharedInvoice =
searchParams.get("data") !== null && !isInvoiceUrlCorrupted;
+ /**
+ * Whether the invoice on screen is still exactly the one opened from a shared link.
+ *
+ * Not the same as {@link isViewingSharedInvoice}: "Get link" puts `?data=` in the address
+ * bar too, but then the invoice is the user's own. Matters for "Invoice last updated",
+ * which comes from this browser's metadata and the link does not carry a timestamp: for
+ * an invoice opened from someone else's link it would show the viewer's own last edit.
+ */
+ const [isUnmodifiedInvoiceFromLink, setIsUnmodifiedInvoiceFromLink] =
+ useState(false);
+
const {
isOpen: isChangelogPopupOpen,
dismiss: dismissChangelogPopup,
@@ -242,14 +254,14 @@ export function AppPageClient({
const parsedData = invoiceSchema.parse(updatedJson);
- const selectedInvoiceData = templateValidation.success
- ? selectInvoiceTemplate(parsedData, templateValidation.data)
+ const selectedInvoiceData = urlTemplate
+ ? selectInvoiceTemplate(parsedData, urlTemplate)
: parsedData;
setInvoiceDataState(selectedInvoiceData);
- } else if (templateValidation.success) {
+ } else if (urlTemplate) {
// if no data in local storage and template is in url, set initial data with template from url
- setInvoiceDataState(getInitialInvoiceData(templateValidation.data));
+ setInvoiceDataState(getInitialInvoiceData(urlTemplate));
} else {
// if no data in local storage, set initial data
setInvoiceDataState(getInitialInvoiceData());
@@ -258,11 +270,7 @@ export function AppPageClient({
console.error("Failed to load saved invoice data:", error);
// fallback to initial data on error
- setInvoiceDataState(
- getInitialInvoiceData(
- templateValidation.success ? templateValidation.data : undefined,
- ),
- );
+ setInvoiceDataState(getInitialInvoiceData(urlTemplate ?? undefined));
toast.error(
"Unable to load your saved invoice data. For your convenience, we've reset the form to default values. Please try creating a new invoice.",
@@ -276,7 +284,7 @@ export function AppPageClient({
Sentry.captureException(error);
}
- }, [templateValidation.data, templateValidation.success]);
+ }, [urlTemplate]);
useEffect(() => {
// Scroll to top of the page on first render for better UX
@@ -288,7 +296,7 @@ export function AppPageClient({
// Run only once per page load.
//
// This effect depends on `searchParams`, and the app rewrites the URL on its own
- // (e.g. to keep ?template= in sync, or to add ?data=
+ // (e.g. to keep the template's route in sync, or to add ?data=
// when a share link is generated). Without this guard, every one of those rewrites
// re-ran the initialization, re-read localStorage and called `setInvoiceDataState`
// with a brand new (but identical) object. That extra state update makes react-pdf
@@ -328,18 +336,18 @@ export function AppPageClient({
validatedDataFromURL,
);
- // Override template from URL parameter if present for better UX
- // The ?template parameter provides a cleaner URL and better user experience
- // while ?data contains the actual invoice data including the template
- // ?template=" " has higher priority than ?data=" " =)
- const selectedInvoiceData = templateValidation.success
- ? selectInvoiceTemplate(validatedDataFromURL, templateValidation.data)
+ // Override template from the URL (`/stripe-template` or ?template=) if present for
+ // better UX, while ?data contains the actual invoice data including the template.
+ // The URL template has higher priority than ?data=" " =)
+ const selectedInvoiceData = urlTemplate
+ ? selectInvoiceTemplate(validatedDataFromURL, urlTemplate)
: validatedDataFromURL;
setInvoiceDataState(selectedInvoiceData);
// Store the original URL invoice data for change detection
originalUrlInvoiceDataRef.current = selectedInvoiceData;
+ setIsUnmodifiedInvoiceFromLink(true);
// add metadata with default values if missing for all users
ensureAppMetadata();
@@ -371,12 +379,17 @@ export function AppPageClient({
window.location.search,
);
clearedParams.delete("data");
- clearedParams.set(
- "template",
- clearedParams.get("template") || "default",
- );
- replaceUrlQuery(clearedParams);
+ replaceUrl(
+ buildInvoiceAppUrl({
+ template:
+ getTemplateFromUrl({
+ pathname: window.location.pathname,
+ searchParams: clearedParams,
+ }) ?? "default",
+ searchParams: clearedParams,
+ }),
+ );
toast.dismiss();
}}
@@ -399,38 +412,93 @@ export function AppPageClient({
// if no data in url, load from local storage
loadFromLocalStorage();
}
- }, [loadFromLocalStorage, searchParams, templateValidation]);
+ }, [loadFromLocalStorage, searchParams, urlTemplate]);
/**
- * Ensures the template query parameter is present in the URL (for better user experience)
- * If missing, adds it based on the current invoice data state.
+ * Ensures the URL is the route of the loaded invoice's template (for better user
+ * experience): `/` or `/stripe-template`. A visitor landing on a bare `/` with a saved
+ * Stripe invoice is moved to `/stripe-template`, and legacy links drop their now
+ * redundant `?template=` (`/?template=default`, or `/?template=stripe` after its
+ * redirect to `/stripe-template?template=stripe`).
*/
useEffect(() => {
- // Only run if we have invoice data and no template in URL.
- //
// `no-event-handler` wants this written where the invoice data is set, but the template
// being written *is* `invoiceDataState.template`, which the initialization effect has not
// resolved yet at that point. (It was also load-bearing back when this used
// `router.replace`, which the App Router dropped when called mid-mount -- under load the
// shared-link e2e tests then sat on a URL that never grew its `?template=`.)
// oxlint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
- if (!invoiceDataState || searchParams.get("template")) {
+ if (!invoiceDataState) {
return;
}
- debugLog("[useEffect] [add missing template to URL]", {
+ // Read the address bar itself, not `pathname`/`searchParams`: Next syncs those with
+ // `history.replaceState` a render later, so right after a template switch this effect
+ // sees the new invoice template next to the *previous* URL. Rebuilding from that stale
+ // URL put back the `?data=` that `handleInvoiceDataChange` had just dropped, leaving an
+ // edited invoice on its old share link.
+ const currentParams = new URLSearchParams(window.location.search);
+
+ if (
+ isUrlForTemplate({
+ template: invoiceDataState.template,
+ pathname: window.location.pathname,
+ searchParams: currentParams,
+ })
+ ) {
+ return;
+ }
+
+ const expectedUrl = buildInvoiceAppUrl({
template: invoiceDataState.template,
+ searchParams: currentParams,
});
- // Create a new URLSearchParams object from the current search parameters
- const currentParams = new URLSearchParams(searchParams.toString());
-
- // Add the template parameter from the invoice data
- currentParams.set("template", invoiceDataState.template);
+ debugLog("[useEffect] [sync template to URL]", {
+ template: invoiceDataState.template,
+ expectedUrl,
+ });
// Update the browser URL without triggering a page reload or scroll
- replaceUrlQuery(currentParams);
- }, [invoiceDataState, searchParams]);
+ replaceUrl(expectedUrl);
+ }, [invoiceDataState]);
+
+ /**
+ * Keeps the tab title and the canonical URL on the route in the address bar. Both come
+ * from the metadata of the route the page was *loaded* on, and a template switch only
+ * rewrites the URL, so a bare `/` that moved on to `/stripe-template` (a saved Stripe
+ * invoice), or a switch in the template picker, would keep the other route's -- the
+ * title is what a bookmark or a history entry gets, and the canonical is what Safari's
+ * own Share (in its menu, not "Get link") copies instead of the address bar.
+ *
+ * Crawlers never see the rewrite: they have no saved invoice and don't switch templates.
+ *
+ * An effect on `pathname` rather than a write in `replaceUrl`: Next re-renders the tree
+ * to sync `usePathname()` with `history.replaceState`, and React puts the metadata's
+ * `<title>` back in that commit. This runs after it.
+ *
+ * Known gap: on a client-side navigation into the app (e.g. "Open app" from another
+ * page), Next can commit the route's metadata later still, putting the loaded route's
+ * title and canonical back.
+ */
+ useEffect(() => {
+ const routeTemplate = getRouteTemplate(pathname);
+
+ document.title = APP_PAGE_TITLE[routeTemplate];
+
+ const canonicalLink = document.querySelector<HTMLLinkElement>(
+ 'link[rel="canonical"]',
+ );
+
+ if (canonicalLink) {
+ // resolved against the current canonical to keep its origin: `APP_URL` comes from a
+ // server-only env var, so the client bundle cannot build it
+ canonicalLink.href = new URL(
+ buildInvoiceAppUrl({ template: routeTemplate }),
+ canonicalLink.href,
+ ).href;
+ }
+ }, [pathname]);
/**
* Checks if the invoice has changed from the original shared URL version.
@@ -460,6 +528,14 @@ export function AppPageClient({
if (invoiceHasChanged) {
debugLog("[checkForInvoiceChanges] invoice has changed");
+ // the edit that got us here also stamped a fresh "Invoice last updated"
+ setIsUnmodifiedInvoiceFromLink(false);
+
+ // the link they confirm no longer matches the invoice
+ for (const toastId of Object.values(SHARE_LINK_SUCCESS_TOAST_IDS)) {
+ toast.dismiss(toastId);
+ }
+
toast.info(
<div className="space-y-2">
<p className="text-sm font-semibold">Invoice Updated</p>
@@ -469,14 +545,14 @@ export function AppPageClient({
<p className="text-muted-foreground text-pretty leading-relaxed">
Click{" "}
- <span className="font-semibold text-foreground">
- &apos;Get link&apos;
+ <span className="font-semibold underline underline-offset-2">
+ Get link
</span>{" "}
to create an updated shareable link.
</p>
</div>,
{
- id: "invoice-has-changed-toast",
+ id: INVOICE_UPDATED_TOAST_ID,
duration: 20_000,
closeButton: true,
position: isMobile ? "top-center" : "bottom-right",
@@ -556,7 +632,10 @@ export function AppPageClient({
setInvoiceDataState(updatedData);
checkForInvoiceChanges(updatedData);
- const currentTemplate = searchParams.get("template");
+ // The template of the route in the address bar: read from `window.location`, which
+ // is never stale (unlike `pathname`, see the URL sync effect), and from the route
+ // alone -- a legacy `?template=` the sync effect has not dropped yet is not a switch.
+ const currentTemplate = getRouteTemplate(window.location.pathname);
// update the url with the new template
if (currentTemplate !== updatedData.template) {
@@ -570,11 +649,16 @@ export function AppPageClient({
// visitor arrived with (utm tags and the like). `data` is still dropped on purpose --
// a template switch is a change from the shared version, which is exactly what
// `checkForInvoiceChanges` above has just told the user about.
- const templateParams = new URLSearchParams(searchParams.toString());
- templateParams.set("template", updatedData.template);
+ const templateParams = new URLSearchParams(window.location.search);
templateParams.delete("data");
- replaceUrlQuery(templateParams);
+ // moves between `/` and `/stripe-template`
+ replaceUrl(
+ buildInvoiceAppUrl({
+ template: updatedData.template,
+ searchParams: templateParams,
+ }),
+ );
} else {
debugLog("[handleInvoiceDataChange] invoice template did not change");
}
@@ -660,10 +744,14 @@ export function AppPageClient({
}
const currentParams = new URLSearchParams(searchParams.toString());
- currentParams.set("template", newInvoiceDataValidated.template);
currentParams.set("data", compressedData);
- replaceUrlQuery(currentParams);
+ const sharedInvoiceUrl = buildInvoiceAppUrl({
+ template: newInvoiceDataValidated.template,
+ searchParams: currentParams,
+ });
+
+ replaceUrl(sharedInvoiceUrl);
// Remember the invoice that was just shared, so later edits are detected and the
// "Invoice Updated" toast is shown. Previously this ref was (re)populated as a
@@ -671,15 +759,23 @@ export function AppPageClient({
// which no longer happens now that initialization runs once per page load.
originalUrlInvoiceDataRef.current = newInvoiceDataValidated;
+ // A new link makes "Invoice Updated" stale. It has to go before the next edit, too:
+ // the form dismisses that toast on every change, right before this page shows it again
+ // under the same id, and sonner treats that as an update to the toast on its way out --
+ // so a second share-then-edit in one session used to end with no toast at all. It also
+ // lets the success toast below come to the front: with `visibleToasts={1}` a toast
+ // updated in place under an existing id stays wherever it was in the stack.
+ toast.dismiss(INVOICE_UPDATED_TOAST_ID);
+
// Construct full URL with locale and compressed data
- const newGeneratedLinkFullUrl = `${window.location.origin}/?${currentParams.toString()}`;
+ const newGeneratedLinkFullUrl = `${window.location.origin}${sharedInvoiceUrl}`;
// allow sharing invoice via navigator.share (on mobile and tablet) or copy to clipboard (on desktop)
if (!isUADesktop && navigator?.share) {
// MOBILE + TABLET
try {
toast.success("Your invoice link is ready. Share it now.", {
- id: "invoice-link-generated-share-invoice-success-toast",
+ id: SHARE_LINK_SUCCESS_TOAST_IDS.shareSheet,
description: (
<p data-testid="share-invoice-link-description-toast">
Share this link to let others view and edit this invoice
@@ -746,7 +842,7 @@ export function AppPageClient({
?.writeText(newGeneratedLinkFullUrl)
.then(() => {
toast.success("Invoice link generated and copied to clipboard!", {
- id: "invoice-link-copied-to-clipboard-success-toast",
+ id: SHARE_LINK_SUCCESS_TOAST_IDS.clipboard,
description: (
<p data-testid="share-invoice-link-description-toast">
Share this link to let others view and edit this invoice
@@ -810,6 +906,7 @@ export function AppPageClient({
isMobile={isMobile}
canShareInvoice={canShareInvoice}
currentInvoiceFormDataRef={currentInvoiceFormDataRef}
+ isUnmodifiedInvoiceFromLink={isUnmodifiedInvoiceFromLink}
mobileDockNotice={isMobile ? changelogPopup : null}
// switching tabs means the user found their way around, so the welcome
// notice has done its job
@@ -819,7 +916,6 @@ export function AppPageClient({
</div>
</main>
</InvoicePdfInstanceProvider>
- <Footer />
{isMobile ? null : changelogPopup}
<HowItWorksVideoDialog
open={isHowItWorksDialogOpen}
@@ -831,3 +927,16 @@ export function AppPageClient({
</TooltipProvider>
);
}
+
+/**
+ * The "Invoice Updated" toast: the invoice no longer matches the shared link it was opened
+ * from (or that was just generated). `invoice-form/index.tsx` dismisses it by this id on
+ * every change.
+ */
+const INVOICE_UPDATED_TOAST_ID = "invoice-has-changed-toast";
+
+/** The toasts confirming a share link: the share sheet (mobile) and the clipboard (desktop). */
+const SHARE_LINK_SUCCESS_TOAST_IDS = {
+ shareSheet: "invoice-link-generated-share-invoice-success-toast",
+ clipboard: "invoice-link-copied-to-clipboard-success-toast",
+} as const;
diff --git a/src/app/(main)/(app)/page.tsx b/src/app/(main)/(app)/page.tsx
index da1b0b4..32998d6 100644
--- a/src/app/(main)/(app)/page.tsx
+++ b/src/app/(main)/(app)/page.tsx
@@ -1,193 +1,9 @@
-import * as Sentry from "@sentry/nextjs";
import type { Metadata } from "next";
-import { fetchGithubStars } from "@/actions/fetch-github-stars";
-import { getLatestChangelogSummary } from "@/app/(main)/changelog/utils";
-import { APP_URL, STATIC_ASSETS_URL, TWITTER_CREATOR } from "@/config";
-import { computeIndexingFlags } from "@/lib/seo/indexing-utils";
+import { buildInvoiceAppMetadata, InvoiceAppPage } from "./invoice-app-page";
-import { CTAToastProvider } from "./contexts/cta-toast-context";
-import { HomeJsonLd } from "./home-json-ld";
-import { AppPageClient } from "./page.client";
-import { RobotsMetaSync } from "./robots-meta-sync";
+export const metadata: Metadata = buildInvoiceAppMetadata("default");
-const APP_PAGE_DESCRIPTION =
- "Create professional PDF invoices online for free. Customize invoice templates, add your logo, download instantly, and send invoices without signup.";
-
-const DEFAULT_TEMPLATE_META = {
- title: "Free Invoice Generator - Create PDF Invoices Online",
- canonical: `${APP_URL}/`, // we use root URL as canonical for SEO purposes
- images: [
- {
- url: `${STATIC_ASSETS_URL}/easy-invoice-opengraph-image.png?v=1755773879597`,
- type: "image/png",
- width: 1200,
- height: 630,
- alt: "Default Invoice Template - EasyInvoicePDF.com",
- },
- ],
-} as const satisfies {
- title: string;
- canonical: string;
- images: NonNullable<Metadata["openGraph"]>["images"];
-};
-
-const STRIPE_TEMPLATE_META = {
- title: "Stripe Invoice Template - Create Free PDF Invoice",
- canonical: `${APP_URL}/?template=stripe`, // self-referencing canonical so the Stripe template is indexed as its own page
- images: [
- {
- url: `${STATIC_ASSETS_URL}/stripe-og.png?v=1755773921680`,
- width: 1200,
- height: 630,
- alt: "Stripe Invoice Template - EasyInvoicePDF.com",
- },
- ],
-} as const satisfies {
- title: string;
- canonical: string;
- images: NonNullable<Metadata["openGraph"]>["images"];
-};
-
-/**
- * Builds complete metadata object for invoice app templates.
- *
- * Constructs OpenGraph and Twitter metadata for template variants
- * (default and Stripe), including title, description, canonical URL,
- * and OG image specifications.
- *
- * @param meta - Template metadata object containing title, canonical URL, and OG images
- * @returns Next.js Metadata object with OpenGraph and Twitter cards configured
- */
-function buildTemplateMetadata(
- meta: typeof DEFAULT_TEMPLATE_META | typeof STRIPE_TEMPLATE_META,
-): Metadata {
- const { title, canonical, images } = meta;
-
- return {
- title,
- description: APP_PAGE_DESCRIPTION,
- alternates: {
- canonical,
- types: {
- "text/markdown": `${APP_URL}/invoice-generator.md`,
- },
- },
- openGraph: {
- title,
- description: APP_PAGE_DESCRIPTION,
- siteName: "EasyInvoicePDF.com | Free Invoice PDF Generator",
- locale: "en_US",
- type: "website",
- url: canonical,
- images: [...images],
- },
- twitter: {
- card: "summary_large_image",
- title,
- description: APP_PAGE_DESCRIPTION,
- creator: TWITTER_CREATOR,
- images: [...images],
- },
- };
-}
-
-/**
- * Resolves `robots` metadata for the main invoice app URL (`/`).
- *
- * Indexing is allowed only when `shouldIndex` is true (production deploy,
- * no shareable `?data=` payload). All non-indexable cases use strict
- * `noindex,nofollow` (including preview builds and share links).
- *
- * @param shouldIndex - Whether this response should be indexable.
- * @returns Next.js `Metadata.robots` object for this page.
- */
-function resolveAppPageRobots(
- shouldIndex: boolean,
-): NonNullable<Metadata["robots"]> {
- if (shouldIndex) {
- return {
- index: true,
- follow: true,
- googleBot: {
- index: true,
- follow: true,
- },
- };
- }
-
- const strictNoIndexNoFollow = {
- index: false,
- follow: false,
- googleBot: {
- index: false,
- follow: false,
- },
- } as const satisfies NonNullable<Metadata["robots"]>;
-
- // if we have shareable data, we don't want to index the page
- // or on non-production environments
- return strictNoIndexNoFollow;
-}
-
-// we generate metadata here, because we need access to searchParams (in layout we don't have it)
-export async function generateMetadata({
- searchParams,
-}: {
- searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
-}): Promise<Metadata> {
- const resolvedSearchParams = await searchParams;
-
- const { shouldIndex } = computeIndexingFlags(resolvedSearchParams);
- const isStripeTemplate = resolvedSearchParams?.template === "stripe";
-
- const templateMetadata = buildTemplateMetadata(
- isStripeTemplate ? STRIPE_TEMPLATE_META : DEFAULT_TEMPLATE_META,
- );
-
- const robots = resolveAppPageRobots(shouldIndex);
-
- return {
- robots,
- ...templateMetadata,
- };
-}
-
-export default async function AppPage({
- searchParams,
-}: {
- searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
-}) {
- const { isIndexableEnvironment, shouldIndex } = computeIndexingFlags(
- await searchParams,
- );
-
- const [githubStarsCount, latestChangelog] = await Promise.all([
- fetchGithubStars(),
- getLatestChangelogSummary().catch((error) => {
- // don't fail the page if we can't load the latest changelog summary
- console.error("[AppPage] Failed to load latest changelog summary", error);
-
- Sentry.captureException(
- new Error(
- `[AppPage] Failed to load latest changelog summary: ${error}`,
- ),
- );
-
- return null;
- }),
- ]);
-
- return (
- <CTAToastProvider>
- {/* sharing an invoice adds `?data=` without a navigation, so the server-rendered
- robots metadata has to be re-applied on the client */}
- <RobotsMetaSync isIndexableEnvironment={isIndexableEnvironment} />
- {shouldIndex ? <HomeJsonLd /> : null}
- <AppPageClient
- githubStarsCount={githubStarsCount}
- latestChangelog={latestChangelog}
- />
- </CTAToastProvider>
- );
+export default function AppPage() {
+ return <InvoiceAppPage template="default" />;
}
diff --git a/src/app/(main)/(app)/robots-meta-sync.tsx b/src/app/(main)/(app)/robots-meta-sync.tsx
deleted file mode 100644
index 3e396bf..0000000
--- a/src/app/(main)/(app)/robots-meta-sync.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-"use client";
-
-import { useSearchParams } from "next/navigation";
-import { useEffect } from "react";
-
-import { ROBOTS_META_CONTENT } from "@/lib/seo/indexing-utils";
-
-/**
- * The meta tags Next.js emits from `Metadata.robots` on this page.
- *
- * `robots` comes from `robots.index`/`robots.follow`, `googlebot` from `robots.googleBot`.
- */
-const ROBOTS_META_NAMES = ["robots", "googlebot"] as const;
-
-/**
- * Writes `content` to every robots meta tag in the document.
- *
- * A tag Next.js did not render is created only for restrictive directives -- an absent
- * tag already means "index, follow", so there is nothing to add in the permissive case.
- *
- * @param content - The crawler directives to apply, e.g. `"noindex, nofollow"`.
- */
-function applyRobotsMetaContent(content: string) {
- const isRestrictive = content === ROBOTS_META_CONTENT.nonIndexable;
-
- for (const name of ROBOTS_META_NAMES) {
- const existingMeta = document.querySelector(`meta[name="${name}"]`);
-
- if (existingMeta) {
- existingMeta.setAttribute("content", content);
- continue;
- }
-
- if (!isRestrictive) {
- continue;
- }
-
- const meta = document.createElement("meta");
- meta.setAttribute("name", name);
- meta.setAttribute("content", content);
- document.head.append(meta);
- }
-}
-
-/**
- * Keeps the crawler directives in sync with the `?data=` share param.
- *
- * `generateMetadata` already renders `noindex, nofollow` for any request that arrives with
- * `?data=`, but sharing an invoice adds that param through `window.history.replaceState`
- * (see `replaceUrlQuery` in `page.client.tsx`) -- a deliberate, navigation-free rewrite, so
- * the server never re-renders the metadata and the document keeps whatever directives it
- * was loaded with. On production that is `index, follow`, which would let a crawler that
- * picked the shared link up index someone's invoice data.
- *
- * The tags are patched in place rather than rendered: Next already owns a `meta[name="robots"]`
- * in the document, and a second one would leave crawlers with two conflicting directives.
- *
- * @returns Nothing -- this component only writes to `document.head`.
- */
-export function RobotsMetaSync({
- isIndexableEnvironment,
-}: {
- /**
- * Whether this deployment is indexable at all -- i.e. the canonical production
- * deployment. Preview deployments are never indexable, with or without `?data=`.
- */
- isIndexableEnvironment: boolean;
-}) {
- const searchParams = useSearchParams();
- const hasShareableData = searchParams.get("data") !== null;
-
- // mirrors what `generateMetadata` would render for the URL currently in the address bar,
- // in both directions -- the app drops `?data=` in place too (a corrupted link, an edit to
- // a shared invoice), and `/` on its own is the canonical page we do want indexed
- const shouldIndex = isIndexableEnvironment && !hasShareableData;
-
- useEffect(() => {
- applyRobotsMetaContent(
- shouldIndex
- ? ROBOTS_META_CONTENT.indexable
- : ROBOTS_META_CONTENT.nonIndexable,
- );
- }, [shouldIndex]);
-
- return null;
-}
diff --git a/src/app/(main)/(app)/stripe-template/page.tsx b/src/app/(main)/(app)/stripe-template/page.tsx
new file mode 100644
index 0000000..e37c1e7
--- /dev/null
+++ b/src/app/(main)/(app)/stripe-template/page.tsx
@@ -0,0 +1,13 @@
+import type { Metadata } from "next";
+
+import { buildInvoiceAppMetadata, InvoiceAppPage } from "../invoice-app-page";
+
+export const metadata: Metadata = buildInvoiceAppMetadata("stripe");
+
+/**
+ * The invoice generator opened on the Stripe template. Same page as `/`; the client
+ * reads the template from the pathname (`getTemplateFromUrl`).
+ */
+export default function StripeTemplateAppPage() {
+ return <InvoiceAppPage template="stripe" />;
+}
diff --git a/src/app/(main)/(seo-landings)/__tests__/seo-landing-counts.test.ts b/src/app/(main)/(seo-landings)/__tests__/seo-landing-counts.test.ts
new file mode 100644
index 0000000..dfbcf40
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/__tests__/seo-landing-counts.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ SUPPORTED_CURRENCIES,
+ SUPPORTED_INVOICE_PDF_LANGUAGES,
+} from "@/app/schema";
+
+import { SEO_LANDING_DEFINITIONS } from "../seo-landing-definitions";
+import {
+ APP_FOOTER_SOLUTION_LINKS,
+ SEO_FOOTER_SOLUTION_LINKS,
+} from "../seo-landing-footer-links";
+
+/**
+ * The landing copy states how many languages and currencies the PDF supports, in prose
+ * ("13 languages"), in facts and comparison tables ("Languages on the PDF: 13") and in the
+ * footer anchors. Those numbers are typed by hand, and adding a language to the schema
+ * left five of them saying 12 -- so they are checked against the schema here.
+ */
+const EXPECTED_COUNTS = {
+ languages: SUPPORTED_INVOICE_PDF_LANGUAGES.length,
+ currencies: SUPPORTED_CURRENCIES.length,
+} as const;
+
+type CountedThing = keyof typeof EXPECTED_COUNTS;
+
+interface CountClaim {
+ /** Where the claim was found, e.g. `stripe-invoice-alternative.factsTable.rows[5]`. */
+ where: string;
+ thing: CountedThing;
+ count: number;
+}
+
+describe("language and currency counts in the SEO copy", () => {
+ const claims = [
+ ...Object.entries(SEO_LANDING_DEFINITIONS).flatMap(([slug, definition]) => {
+ return collectCountClaims({ value: definition, where: slug });
+ }),
+ ...[...APP_FOOTER_SOLUTION_LINKS, ...SEO_FOOTER_SOLUTION_LINKS].flatMap(
+ ({ label }) => {
+ return collectCountClaims({ value: label, where: `footer "${label}"` });
+ },
+ ),
+ ];
+
+ it.each(Object.keys(EXPECTED_COUNTS) as CountedThing[])(
+ "finds the %s claims it checks",
+ (thing) => {
+ // guards the scan itself: if the copy is restructured and nothing matches any more,
+ // the test below would pass on an empty list
+ expect(claimsAbout({ claims, thing }).length).toBeGreaterThan(5);
+ },
+ );
+
+ it.each(Object.keys(EXPECTED_COUNTS) as CountedThing[])(
+ "states the real number of %s everywhere",
+ (thing) => {
+ expect(
+ claimsAbout({ claims, thing }).filter(({ count }) => {
+ return count !== EXPECTED_COUNTS[thing];
+ }),
+ ).toEqual([]);
+ },
+ );
+});
+
+interface ClaimsAboutParams {
+ claims: CountClaim[];
+ thing: CountedThing;
+}
+
+function claimsAbout({ claims, thing }: ClaimsAboutParams) {
+ return claims.filter((claim) => {
+ return claim.thing === thing;
+ });
+}
+
+interface CollectCountClaimsParams {
+ value: unknown;
+ /** Path to `value`, for the failure message. */
+ where: string;
+}
+
+/**
+ * Walks the landing copy and returns every number it states for languages or currencies:
+ * "13 languages" in any string, and the number in a table row labelled with the thing
+ * ("Languages on the PDF" -> "✅ 13").
+ *
+ * Embedded videos are skipped: their title and description are the published YouTube
+ * metadata (one says "10 languages"), not copy we can keep current.
+ *
+ * @returns The claims found in `value` and everything below it.
+ */
+function collectCountClaims({
+ value,
+ where,
+}: CollectCountClaimsParams): CountClaim[] {
+ if (typeof value === "string") {
+ return [...value.matchAll(/(\d+)\s+(languages|currencies)\b/gi)].map(
+ ([, count, thing]) => {
+ return {
+ where,
+ thing: thing.toLowerCase() as CountedThing,
+ count: Number(count),
+ };
+ },
+ );
+ }
+
+ if (Array.isArray(value)) {
+ return value.flatMap((item, index) => {
+ return collectCountClaims({ value: item, where: `${where}[${index}]` });
+ });
+ }
+
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+
+ const record = value as Record<string, unknown>;
+ const claims: CountClaim[] = [];
+
+ // a table row: { label | feature: "Languages on the PDF", value | thisTool: "✅ 13" }
+ const rowLabel = record.label ?? record.feature;
+ const rowValue = record.value ?? record.thisTool;
+
+ if (typeof rowLabel === "string" && typeof rowValue === "string") {
+ const thing = /languages/i.test(rowLabel)
+ ? "languages"
+ : /currencies/i.test(rowLabel)
+ ? "currencies"
+ : null;
+ const count = /\d+/.exec(rowValue)?.[0];
+
+ if (thing && count) {
+ claims.push({ where, thing, count: Number(count) });
+ }
+ }
+
+ for (const [key, child] of Object.entries(record)) {
+ if (key === "heroVideo" || key === "video") {
+ continue;
+ }
+
+ claims.push(
+ ...collectCountClaims({ value: child, where: `${where}.${key}` }),
+ );
+ }
+
+ return claims;
+}
diff --git a/src/app/(main)/(seo-landings)/__tests__/seo-landing-h1-marks.test.ts b/src/app/(main)/(seo-landings)/__tests__/seo-landing-h1-marks.test.ts
new file mode 100644
index 0000000..6ecffb0
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/__tests__/seo-landing-h1-marks.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ SEO_LANDING_DEFINITIONS,
+ SEO_LANDING_SLUGS,
+} from "../seo-landing-definitions";
+
+describe("h1 marks on the SEO landings", () => {
+ it.each(SEO_LANDING_SLUGS)("%s marks a phrase that is in its h1", (slug) => {
+ const { h1, h1Mark } = SEO_LANDING_DEFINITIONS[slug].hero;
+
+ expect(h1).toContain(h1Mark.phrase);
+ });
+
+ it("gives every landing its own mark type and colour pairing", () => {
+ const pairings = SEO_LANDING_SLUGS.map((slug) => {
+ const { type, color } = SEO_LANDING_DEFINITIONS[slug].hero.h1Mark;
+ return `${type} ${color}`;
+ });
+
+ expect(new Set(pairings).size).toBe(pairings.length);
+ });
+});
+
+/**
+ * See `h1Mark.phrase`: the mark's SVG sits before a highlight and after an underline, and
+ * counts as a word break in the heading's accessible name there, so that side of the
+ * phrase must already be whitespace (or the edge of the heading).
+ */
+describe("h1 mark phrases keep the heading's accessible name intact", () => {
+ it.each(slugsMarkedWith("highlight"))(
+ "%s: a space or the start of the heading comes before the highlight",
+ (slug) => {
+ const { h1, h1Mark } = SEO_LANDING_DEFINITIONS[slug].hero;
+
+ expect(` ${h1}`).toContain(` ${h1Mark.phrase}`);
+ },
+ );
+
+ it.each(slugsMarkedWith("underline"))(
+ "%s: a space or the end of the heading comes after the underline",
+ (slug) => {
+ const { h1, h1Mark } = SEO_LANDING_DEFINITIONS[slug].hero;
+
+ expect(`${h1} `).toContain(`${h1Mark.phrase} `);
+ },
+ );
+});
+
+function slugsMarkedWith(type: "highlight" | "underline") {
+ return SEO_LANDING_SLUGS.filter((slug) => {
+ return SEO_LANDING_DEFINITIONS[slug].hero.h1Mark.type === type;
+ });
+}
diff --git a/src/app/(main)/(seo-landings)/__tests__/seo-landing-related.test.ts b/src/app/(main)/(seo-landings)/__tests__/seo-landing-related.test.ts
new file mode 100644
index 0000000..8d36d2c
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/__tests__/seo-landing-related.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ SEO_LANDING_DEFINITIONS,
+ SEO_LANDING_SLUGS,
+} from "../seo-landing-definitions";
+import { SEO_FOOTER_SOLUTION_LINKS } from "../seo-landing-footer-links";
+
+describe("related landing links", () => {
+ const footerSlugs = new Set<string>(
+ SEO_FOOTER_SOLUTION_LINKS.map(({ slug }) => {
+ return slug;
+ }),
+ );
+
+ it.each(SEO_LANDING_SLUGS)(
+ "%s links to other landings, once each",
+ (slug) => {
+ const { relatedSlugs } = SEO_LANDING_DEFINITIONS[slug];
+
+ expect(relatedSlugs.length).toBeGreaterThan(0);
+ expect(relatedSlugs).not.toContain(slug);
+ expect(new Set(relatedSlugs).size).toBe(relatedSlugs.length);
+ },
+ );
+
+ it("has a footer label for every landing, which the related block uses as anchor text", () => {
+ expect(
+ SEO_LANDING_SLUGS.filter((slug) => {
+ return !footerSlugs.has(slug);
+ }),
+ ).toEqual([]);
+ });
+
+ it("links every landing from at least one other landing", () => {
+ const linked = new Set(
+ Object.values(SEO_LANDING_DEFINITIONS).flatMap(({ relatedSlugs }) => {
+ return [...relatedSlugs];
+ }),
+ );
+
+ expect(
+ SEO_LANDING_SLUGS.filter((slug) => {
+ return !linked.has(slug);
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/src/app/(main)/(seo-landings)/build-seo-landing-json-ld.ts b/src/app/(main)/(seo-landings)/build-seo-landing-json-ld.ts
index 4a6dede..cb1c2f4 100644
--- a/src/app/(main)/(seo-landings)/build-seo-landing-json-ld.ts
+++ b/src/app/(main)/(seo-landings)/build-seo-landing-json-ld.ts
@@ -103,6 +103,10 @@ export function buildSeoLandingJsonLd(
mainEntity: {
"@id": isOpenSourceLanding ? pageSoftwareAppId(pageUrl) : faqUrl,
},
+ // the same pages the "Related" block under the FAQ links to
+ relatedLink: definition.relatedSlugs.map((slug) => {
+ return `${baseUrl}/${slug}`;
+ }),
};
const faqPage = {
@@ -111,10 +115,13 @@ export function buildSeoLandingJsonLd(
mainEntity: faqEntities,
};
- const breadcrumb = buildBreadcrumbList(pageUrl, [
- { name: "Start Invoicing", item: `${baseUrl}/` },
- { name: definition.metadata.title },
- ]);
+ const breadcrumb = buildBreadcrumbList({
+ pageUrl,
+ items: [
+ { name: "Start Invoicing", item: `${baseUrl}/` },
+ { name: definition.metadata.title },
+ ],
+ });
const heroVideo = definition.hero.heroVideo;
diff --git a/src/app/(main)/(seo-landings)/components/seo-landing-shell.tsx b/src/app/(main)/(seo-landings)/components/seo-landing-shell.tsx
index eb92dc6..10761f6 100644
--- a/src/app/(main)/(seo-landings)/components/seo-landing-shell.tsx
+++ b/src/app/(main)/(seo-landings)/components/seo-landing-shell.tsx
@@ -10,6 +10,7 @@ import {
type RoughAnnotationType,
RoughAnnotation,
} from "@/components/rough-annotation";
+import { TrackClick } from "@/components/track-click";
import { Button } from "@/components/ui/button";
import { FaqAccordion, FaqAccordionItem } from "@/components/ui/faq-accordion";
import { YouTubeEmbed } from "@/components/youtube-embed";
@@ -18,8 +19,10 @@ import { GITHUB_URL } from "@/config";
import {
type ComparisonTable,
type SeoLandingDefinition,
+ type SeoLandingSlug,
type SeoSection,
} from "../seo-landing-definitions";
+import { SEO_FOOTER_SOLUTION_LINKS } from "../seo-landing-footer-links";
import { SeoLandingJsonLd } from "./seo-landing-json-ld";
interface SeoLandingShellProps {
@@ -58,7 +61,10 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
<div className="border-b border-slate-200 bg-white">
<div className="container mx-auto max-w-4xl px-4 pb-6 pt-12 md:px-6 md:py-16 md:pb-8">
<h1 className="text-balance text-4xl font-bold tracking-tight text-slate-900 md:text-5xl">
- {definition.hero.h1}
+ <MarkedHeading
+ text={definition.hero.h1}
+ mark={definition.hero.h1Mark}
+ />
</h1>
{/*
The hero's opening paragraph, not a heading. It runs to a couple of
@@ -72,12 +78,19 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
className="mt-8 flex flex-col gap-4 md:flex-row"
{...seoHeroCtaMarker}
>
- <BlackGoToAppButton
- className="w-full px-8 py-6 text-base lg:w-[325px] lg:px-10"
- href={definition.hero.ctaHref}
+ <TrackClick
+ {...ctaClickEvent({
+ slug: definition.slug,
+ position: "hero",
+ })}
>
- <span className="truncate">{definition.hero.ctaLabel}</span>
- </BlackGoToAppButton>
+ <BlackGoToAppButton
+ className="w-full px-8 py-6 text-base lg:w-[325px] lg:px-10"
+ href={definition.hero.ctaHref}
+ >
+ <span className="truncate">{definition.hero.ctaLabel}</span>
+ </BlackGoToAppButton>
+ </TrackClick>
<Button
size="lg"
variant="outline"
@@ -94,6 +107,38 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
</Link>
</Button>
</div>
+ {definition.hero.downloads ? (
+ <p
+ className="mt-4 text-pretty text-base text-slate-600"
+ data-testid="seo-landing-hero-downloads"
+ >
+ {definition.hero.downloads.label}{" "}
+ {definition.hero.downloads.files.map((file, index) => {
+ return (
+ <span key={file.href}>
+ {index > 0 ? " · " : null}
+ {/* a plain anchor: a route handler, not a page, and `download`
+ saves the file instead of opening it */}
+ <TrackClick
+ event="seo_landing_file_downloaded"
+ data={{
+ slug: definition.slug,
+ file: file.href.split("/").at(-1) ?? file.href,
+ }}
+ >
+ <a
+ href={file.href}
+ download
+ className="font-medium text-slate-900 underline underline-offset-4 hover:text-slate-600"
+ >
+ {file.label}
+ </a>
+ </TrackClick>
+ </span>
+ );
+ })}
+ </p>
+ ) : null}
{definition.hero.heroVideo ? (
<div className="mt-8 aspect-video overflow-hidden rounded-lg bg-slate-100/80 shadow-sm">
<YouTubeEmbed
@@ -179,6 +224,7 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
<SeoInlineCta
href={definition.hero.ctaHref}
label={definition.hero.ctaLabel}
+ slug={definition.slug}
/>
) : null}
{canShowComparisonTable && comparisonTable ? (
@@ -235,13 +281,22 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
</FaqAccordion>
</section>
+ <SeoRelatedLinks slugs={definition.relatedSlugs} />
+
<div className="flex justify-center py-6 md:py-12">
- <BlackGoToAppButton
- className="h-12 w-full px-8 text-base"
- href={definition.hero.ctaHref}
+ <TrackClick
+ {...ctaClickEvent({
+ slug: definition.slug,
+ position: "bottom",
+ })}
>
- {definition.hero.ctaLabel}
- </BlackGoToAppButton>
+ <BlackGoToAppButton
+ className="h-12 w-full px-8 text-base"
+ href={definition.hero.ctaHref}
+ >
+ {definition.hero.ctaLabel}
+ </BlackGoToAppButton>
+ </TrackClick>
</div>
</div>
</main>
@@ -252,8 +307,122 @@ export function SeoLandingShell({ definition }: SeoLandingShellProps) {
);
}
+/**
+ * Links to the landings listed in `relatedSlugs`, under the FAQ.
+ *
+ * The anchor text is the footer's label for each page, which names what sits on the
+ * other end (see `SEO_FOOTER_SOLUTION_LINKS`).
+ */
+function SeoRelatedLinks({ slugs }: { slugs: readonly SeoLandingSlug[] }) {
+ if (slugs.length === 0) {
+ return null;
+ }
+
+ return (
+ <section
+ className="border-t border-slate-100 pt-10"
+ aria-labelledby="seo-landing-related-heading"
+ data-testid="seo-landing-related"
+ >
+ <h2
+ id="seo-landing-related-heading"
+ className="text-2xl font-semibold tracking-tight text-slate-900 md:text-3xl"
+ >
+ Related
+ </h2>
+ <ul className="mt-4 space-y-2 text-base">
+ {slugs.map((slug) => {
+ return (
+ <li key={slug}>
+ <Link
+ href={`/${slug}`}
+ className="font-medium text-slate-900 underline underline-offset-4 hover:text-slate-600"
+ >
+ {SEO_FOOTER_LABEL_BY_SLUG[slug]}
+ </Link>
+ </li>
+ );
+ })}
+ </ul>
+ </section>
+ );
+}
+
+const SEO_FOOTER_LABEL_BY_SLUG = Object.fromEntries(
+ SEO_FOOTER_SOLUTION_LINKS.map(({ slug, label }) => {
+ return [slug, label];
+ }),
+) as Record<SeoLandingSlug, string>;
+
+/**
+ * The h1 text with its mark drawn on one phrase, see `hero.h1Mark`.
+ *
+ * Only the phrase is wrapped, so the heading's text (and its accessible name) is exactly
+ * `hero.h1` with or without the mark. A phrase that is not in the heading renders the
+ * plain text; `seo-landing-h1-marks.test.ts` fails before that ships.
+ */
+function MarkedHeading({
+ text,
+ mark,
+}: {
+ text: string;
+ mark: SeoLandingDefinition["hero"]["h1Mark"];
+}) {
+ const start = text.indexOf(mark.phrase);
+
+ if (start === -1) {
+ return text;
+ }
+
+ return (
+ <>
+ {text.slice(0, start)}
+ <RoughAnnotation
+ type={mark.type}
+ color={mark.color}
+ // after the hero has painted, so the drawing is seen rather than missed on load
+ delayMs={H1_MARK_DELAY_MS}
+ animationDuration={1000}
+ strokeWidth={mark.type === "underline" ? 3 : undefined}
+ // the heading's lines sit close together: a wider gap would reach the next line
+ padding={mark.type === "underline" ? 2 : 4}
+ >
+ {mark.phrase}
+ </RoughAnnotation>
+ {text.slice(start + mark.phrase.length)}
+ </>
+ );
+}
+
+const H1_MARK_DELAY_MS = 300;
+
+/**
+ * The Umami event for a click on one of the landing's in-page CTAs, which open the app.
+ *
+ * `seo_sticky_cta_clicked` covers the sticky bar; together they show how many readers of a
+ * landing go on to the generator, to set against `seo_landing_file_downloaded` on pages
+ * that offer a file.
+ */
+function ctaClickEvent({
+ slug,
+ position,
+}: {
+ slug: SeoLandingSlug;
+ position: "hero" | "inline" | "bottom";
+}) {
+ return { event: "seo_landing_cta_clicked", data: { slug, position } };
+}
+
/** Mid-page prompt to open the app, shown once between the sections. */
-function SeoInlineCta({ href, label }: { href: string; label: string }) {
+function SeoInlineCta({
+ href,
+ label,
+ slug,
+}: {
+ href: string;
+ label: string;
+ slug: SeoLandingSlug;
+}) {
return (
<div
className="my-6 flex flex-col gap-3 rounded-xl border border-slate-200 bg-white p-5 shadow-sm sm:flex-row sm:items-center sm:justify-between sm:gap-6"
@@ -268,12 +437,14 @@ function SeoInlineCta({ href, label }: { href: string; label: string }) {
No account needed.
</p>
</div>
- <BlackGoToAppButton
- className="w-full shrink-0 px-6 py-5 text-base sm:w-auto"
- href={href}
- >
- <span className="truncate">{label}</span>
- </BlackGoToAppButton>
+ <TrackClick {...ctaClickEvent({ slug, position: "inline" })}>
+ <BlackGoToAppButton
+ className="w-full shrink-0 px-6 py-5 text-base sm:w-auto"
+ href={href}
+ >
+ <span className="truncate">{label}</span>
+ </BlackGoToAppButton>
+ </TrackClick>
</div>
);
}
diff --git a/src/app/(main)/(seo-landings)/components/sticky-seo-cta.tsx b/src/app/(main)/(seo-landings)/components/sticky-seo-cta.tsx
index 4034555..46ae626 100644
--- a/src/app/(main)/(seo-landings)/components/sticky-seo-cta.tsx
+++ b/src/app/(main)/(seo-landings)/components/sticky-seo-cta.tsx
@@ -94,7 +94,7 @@ export function StickySeoCta({
<Button
asChild
size="sm"
- className="h-9 min-w-0 rounded-full border border-white/40 !bg-zinc-900 px-4 text-sm text-white hover:bg-white/10 hover:text-white"
+ className="group h-9 min-w-0 rounded-full border border-white/40 !bg-zinc-900 px-4 text-sm text-white hover:bg-white/10 hover:text-white"
>
<Link
href={href}
@@ -106,7 +106,22 @@ export function StickySeoCta({
}}
>
<span className="truncate">{label}</span>
- <ArrowRight className="ml-1.5 size-4" aria-hidden="true" />
+ {/*
+ Same periodic nudge as the header's "Open app" button. The class is only
+ applied while the bar is up, so the animation restarts each time it appears
+ instead of running unseen from mount. The keyframes sit idle for the first
+ 70% (3.5s), so the negative delay skips that, minus the 300ms fade-in and a
+ 500ms pause, so the first nudge lands half a second after the bar settles.
+ */}
+ <ArrowRight
+ className={cn(
+ "ml-1.5 size-4 transition-transform group-hover:scale-110",
+ isVisible
+ ? "animate-pulse-arrow [animation-delay:-2.7s] motion-reduce:animate-none"
+ : null,
+ )}
+ aria-hidden="true"
+ />
</Link>
</Button>
</div>
diff --git a/src/app/(main)/(seo-landings)/contractor-invoice-template/page.tsx b/src/app/(main)/(seo-landings)/contractor-invoice-template/page.tsx
new file mode 100644
index 0000000..b33e095
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/contractor-invoice-template/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("contractor-invoice-template");
+};
+
+export default function ContractorInvoiceTemplatePage() {
+ return <SeoLandingRoutePage slug="contractor-invoice-template" />;
+}
diff --git a/src/app/(main)/(seo-landings)/export-invoice-format/page.tsx b/src/app/(main)/(seo-landings)/export-invoice-format/page.tsx
new file mode 100644
index 0000000..15c8749
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/export-invoice-format/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("export-invoice-format");
+};
+
+export default function ExportInvoiceFormatPage() {
+ return <SeoLandingRoutePage slug="export-invoice-format" />;
+}
diff --git a/src/app/(main)/(seo-landings)/freelance-invoice-template/page.tsx b/src/app/(main)/(seo-landings)/freelance-invoice-template/page.tsx
new file mode 100644
index 0000000..da13463
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/freelance-invoice-template/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("freelance-invoice-template");
+};
+
+export default function FreelanceInvoiceTemplatePage() {
+ return <SeoLandingRoutePage slug="freelance-invoice-template" />;
+}
diff --git a/src/app/(main)/(seo-landings)/german-invoice-generator/page.tsx b/src/app/(main)/(seo-landings)/german-invoice-generator/page.tsx
new file mode 100644
index 0000000..236b955
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/german-invoice-generator/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("german-invoice-generator");
+};
+
+export default function GermanInvoiceGeneratorPage() {
+ return <SeoLandingRoutePage slug="german-invoice-generator" />;
+}
diff --git a/src/app/(main)/(seo-landings)/invoice-template-pdf/__tests__/blank-invoice-pdf.test.ts b/src/app/(main)/(seo-landings)/invoice-template-pdf/__tests__/blank-invoice-pdf.test.ts
new file mode 100644
index 0000000..feebf8a
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/invoice-template-pdf/__tests__/blank-invoice-pdf.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ BLANK_INVOICE_PAGE_SIZES,
+ renderBlankInvoicePdf,
+} from "../blank-invoice-pdf";
+
+/**
+ * 3 header fields, 5 per party block, 4 per line item across 10 rows, 3 totals, and
+ * payment details plus notes.
+ */
+const EXPECTED_FIELD_COUNT = 3 + 5 * 2 + 4 * 10 + 3 + 2;
+
+describe("blank invoice template PDF", () => {
+ it.each(BLANK_INVOICE_PAGE_SIZES)(
+ "renders a one-page fillable PDF on %s paper",
+ async (pageSize) => {
+ const pdf = (await renderBlankInvoicePdf({ pageSize })).toString(
+ "latin1",
+ );
+
+ expect(pdf.startsWith("%PDF-")).toBe(true);
+ // one page: the layout must not spill onto a second sheet when printed
+ expect(pdf.match(/\/Type \/Page\b/g)).toHaveLength(1);
+ expect(pdf).toContain("/AcroForm");
+ expect(pdf.match(/\/FT \/Tx/g)).toHaveLength(EXPECTED_FIELD_COUNT);
+ },
+ 30_000,
+ );
+});
diff --git a/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf-response.ts b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf-response.ts
new file mode 100644
index 0000000..0fcb115
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf-response.ts
@@ -0,0 +1,29 @@
+import { renderBlankInvoicePdf } from "./blank-invoice-pdf";
+
+interface BlankInvoicePdfResponseParams {
+ /** Paper size to render. */
+ pageSize: Parameters<typeof renderBlankInvoicePdf>[0]["pageSize"];
+ /** The name a browser saves the file under; matches the URL's last segment. */
+ fileName: string;
+}
+
+/**
+ * The blank invoice PDF as an HTTP response.
+ *
+ * `inline` so a click opens it in the browser's PDF viewer, where it can be filled in
+ * straight away; the download links on the landing page carry a `download` attribute to
+ * save it instead.
+ */
+export async function blankInvoicePdfResponse({
+ pageSize,
+ fileName,
+}: BlankInvoicePdfResponseParams) {
+ const pdf = await renderBlankInvoicePdf({ pageSize });
+
+ return new Response(new Uint8Array(pdf), {
+ headers: {
+ "Content-Type": "application/pdf",
+ "Content-Disposition": `inline; filename="${fileName}"`,
+ },
+ });
+}
diff --git a/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf.tsx b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf.tsx
new file mode 100644
index 0000000..19029a4
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-pdf.tsx
@@ -0,0 +1,386 @@
+// IMPORTANT: rendered only on the server, at build time, by the route handlers next to
+// this file -- the same exception `render-pdf-on-server.tsx` makes
+// eslint-disable-next-line no-restricted-imports
+import {
+ Document,
+ Link,
+ Page,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+ renderToBuffer,
+} from "@react-pdf/renderer";
+
+import { PROD_WEBSITE_URL } from "@/config";
+
+/**
+ * Paper sizes the blank template is offered in: A4 for most of the world, Letter for the
+ * US and Canada, where "invoice template pdf" searchers print on Letter paper.
+ */
+export const BLANK_INVOICE_PAGE_SIZES = ["A4", "LETTER"] as const;
+
+type BlankInvoicePageSize = (typeof BLANK_INVOICE_PAGE_SIZES)[number];
+
+/** Empty line-item rows: enough for most invoices without crowding the page. */
+const ITEM_ROW_COUNT = 10;
+
+/**
+ * Renders the blank invoice template as a PDF buffer.
+ *
+ * The document is both fillable and printable. Every value is an AcroForm text field,
+ * so it can be typed into in any PDF reader, and each field sits on a ruled line, so a
+ * printed copy can be filled in by hand. It uses the PDF standard font (Helvetica), so
+ * nothing is fetched while rendering and the build has no network dependency.
+ *
+ * It does not total anything: a form field cannot do the math reliably across PDF
+ * readers. The footer points to the generator, which does.
+ */
+export function renderBlankInvoicePdf({
+ pageSize,
+}: {
+ pageSize: BlankInvoicePageSize;
+}) {
+ return renderToBuffer(<BlankInvoiceDocument pageSize={pageSize} />);
+}
+
+function BlankInvoiceDocument({
+ pageSize,
+}: {
+ pageSize: BlankInvoicePageSize;
+}) {
+ return (
+ <Document
+ title="Blank Invoice Template"
+ author="EasyInvoicePDF.com"
+ subject="A free blank invoice template you can fill in or print"
+ creator="EasyInvoicePDF.com"
+ producer="EasyInvoicePDF.com"
+ >
+ <Page size={pageSize} style={styles.page}>
+ <View style={styles.header}>
+ <Text style={styles.title}>INVOICE</Text>
+ <View style={styles.headerFields}>
+ <LabelledField label="Invoice no." name="invoiceNumber" />
+ <LabelledField label="Date of issue" name="dateOfIssue" />
+ <LabelledField label="Due date" name="dueDate" />
+ </View>
+ </View>
+
+ <View style={styles.parties}>
+ <PartyBlock heading="From" prefix="seller" />
+ <PartyBlock heading="Bill to" prefix="buyer" />
+ </View>
+
+ <View style={styles.table}>
+ <View style={[styles.row, styles.tableHead]}>
+ <Text style={[styles.cell, styles.colNo]}>#</Text>
+ <Text style={[styles.cell, styles.colDescription]}>
+ Description
+ </Text>
+ <Text style={[styles.cell, styles.colQty]}>Qty</Text>
+ <Text style={[styles.cell, styles.colPrice]}>Unit price</Text>
+ <Text style={[styles.cell, styles.colAmount]}>Amount</Text>
+ </View>
+ {Array.from({ length: ITEM_ROW_COUNT }, (_, index) => {
+ const rowNumber = index + 1;
+
+ return (
+ <View key={rowNumber} style={styles.row}>
+ <Text style={[styles.cell, styles.colNo, styles.rowNumber]}>
+ {rowNumber}
+ </Text>
+ <FieldCell
+ name={`item${rowNumber}Description`}
+ style={styles.colDescription}
+ />
+ <FieldCell
+ name={`item${rowNumber}Quantity`}
+ style={styles.colQty}
+ align="right"
+ />
+ <FieldCell
+ name={`item${rowNumber}UnitPrice`}
+ style={styles.colPrice}
+ align="right"
+ />
+ <FieldCell
+ name={`item${rowNumber}Amount`}
+ style={styles.colAmount}
+ align="right"
+ />
+ </View>
+ );
+ })}
+ </View>
+
+ <View style={styles.totals}>
+ <TotalRow label="Subtotal" name="subtotal" />
+ <TotalRow label="Tax" name="tax" />
+ <TotalRow label="Total due" name="total" isEmphasized />
+ </View>
+
+ <View style={styles.bottom}>
+ <View style={styles.bottomBlock}>
+ <Text style={styles.blockHeading}>Payment details</Text>
+ <TextInput
+ name="paymentDetails"
+ multiline
+ fontSize={9}
+ style={styles.multilineField}
+ />
+ </View>
+ <View style={styles.bottomBlock}>
+ <Text style={styles.blockHeading}>Notes</Text>
+ <TextInput
+ name="notes"
+ multiline
+ fontSize={9}
+ style={styles.multilineField}
+ />
+ </View>
+ </View>
+
+ <Text style={styles.footer} fixed>
+ Rather not do the math? Fill it in online and download the PDF, free
+ and with no sign up, at{" "}
+ <Link src={`${PROD_WEBSITE_URL}/invoice-template-pdf`}>
+ easyinvoicepdf.com
+ </Link>
+ </Text>
+ </Page>
+ </Document>
+ );
+}
+
+function LabelledField({ label, name }: { label: string; name: string }) {
+ return (
+ <View style={styles.labelledField}>
+ <Text style={styles.label}>{label}</Text>
+ <TextInput name={name} fontSize={9} style={styles.lineField} />
+ </View>
+ );
+}
+
+function PartyBlock({ heading, prefix }: { heading: string; prefix: string }) {
+ return (
+ <View style={styles.party}>
+ <Text style={styles.blockHeading}>{heading}</Text>
+ <PartyLine label="Name" name={`${prefix}Name`} />
+ <PartyLine label="Address" name={`${prefix}AddressLine1`} />
+ <PartyLine label="" name={`${prefix}AddressLine2`} />
+ <PartyLine label="Tax ID" name={`${prefix}TaxId`} />
+ <PartyLine label="Email" name={`${prefix}Email`} />
+ </View>
+ );
+}
+
+function PartyLine({ label, name }: { label: string; name: string }) {
+ return (
+ <View style={styles.partyLine}>
+ <Text style={styles.partyLabel}>{label}</Text>
+ <TextInput name={name} fontSize={9} style={styles.partyField} />
+ </View>
+ );
+}
+
+function FieldCell({
+ name,
+ style,
+ align = "left",
+}: {
+ name: string;
+ style: (typeof styles)[keyof typeof styles];
+ align?: "left" | "right";
+}) {
+ return (
+ <View style={[styles.cell, style]}>
+ <TextInput
+ name={name}
+ align={align}
+ fontSize={9}
+ style={styles.cellField}
+ />
+ </View>
+ );
+}
+
+function TotalRow({
+ label,
+ name,
+ isEmphasized = false,
+}: {
+ label: string;
+ name: string;
+ isEmphasized?: boolean;
+}) {
+ return (
+ <View
+ style={[styles.totalRow, isEmphasized ? styles.totalRowEmphasized : {}]}
+ >
+ <Text style={[styles.totalLabel, isEmphasized ? styles.bold : {}]}>
+ {label}
+ </Text>
+ <TextInput
+ name={name}
+ align="right"
+ fontSize={isEmphasized ? 11 : 9}
+ style={styles.totalField}
+ />
+ </View>
+ );
+}
+
+const INK = "#0f172a";
+const MUTED = "#64748b";
+const RULE = "#cbd5e1";
+
+const styles = StyleSheet.create({
+ page: {
+ paddingTop: 44,
+ paddingBottom: 56,
+ paddingHorizontal: 44,
+ fontFamily: "Helvetica",
+ fontSize: 9,
+ color: INK,
+ },
+ header: {
+ flexDirection: "row",
+ justifyContent: "space-between",
+ alignItems: "flex-start",
+ marginBottom: 28,
+ },
+ title: {
+ fontFamily: "Helvetica-Bold",
+ fontSize: 26,
+ letterSpacing: 2,
+ },
+ headerFields: {
+ width: 220,
+ gap: 6,
+ },
+ labelledField: {
+ flexDirection: "row",
+ alignItems: "flex-end",
+ },
+ label: {
+ width: 80,
+ color: MUTED,
+ },
+ lineField: {
+ flex: 1,
+ height: 16,
+ borderBottomWidth: 1,
+ borderBottomColor: RULE,
+ },
+ parties: {
+ flexDirection: "row",
+ gap: 28,
+ marginBottom: 24,
+ },
+ party: {
+ flex: 1,
+ },
+ blockHeading: {
+ fontFamily: "Helvetica-Bold",
+ fontSize: 10,
+ marginBottom: 6,
+ },
+ partyLine: {
+ flexDirection: "row",
+ alignItems: "flex-end",
+ marginTop: 4,
+ },
+ partyLabel: {
+ width: 46,
+ color: MUTED,
+ },
+ partyField: {
+ flex: 1,
+ height: 16,
+ borderBottomWidth: 1,
+ borderBottomColor: RULE,
+ },
+ table: {
+ borderTopWidth: 1,
+ borderTopColor: INK,
+ },
+ tableHead: {
+ fontFamily: "Helvetica-Bold",
+ borderBottomColor: INK,
+ },
+ row: {
+ flexDirection: "row",
+ borderBottomWidth: 1,
+ borderBottomColor: RULE,
+ minHeight: 22,
+ alignItems: "center",
+ },
+ cell: {
+ paddingHorizontal: 4,
+ },
+ cellField: {
+ height: 18,
+ },
+ rowNumber: {
+ color: MUTED,
+ },
+ colNo: { width: "6%" },
+ colDescription: { width: "46%" },
+ colQty: { width: "12%", textAlign: "right" },
+ colPrice: { width: "18%", textAlign: "right" },
+ colAmount: { width: "18%", textAlign: "right" },
+ totals: {
+ alignSelf: "flex-end",
+ width: 220,
+ marginTop: 14,
+ },
+ totalRow: {
+ flexDirection: "row",
+ alignItems: "flex-end",
+ marginTop: 4,
+ },
+ totalRowEmphasized: {
+ marginTop: 8,
+ paddingTop: 6,
+ borderTopWidth: 1,
+ borderTopColor: INK,
+ },
+ totalLabel: {
+ width: 90,
+ color: MUTED,
+ },
+ bold: {
+ fontFamily: "Helvetica-Bold",
+ color: INK,
+ },
+ totalField: {
+ flex: 1,
+ height: 18,
+ borderBottomWidth: 1,
+ borderBottomColor: RULE,
+ },
+ bottom: {
+ flexDirection: "row",
+ gap: 28,
+ marginTop: 28,
+ },
+ bottomBlock: {
+ flex: 1,
+ },
+ multilineField: {
+ height: 64,
+ borderWidth: 1,
+ borderColor: RULE,
+ borderRadius: 2,
+ },
+ footer: {
+ position: "absolute",
+ bottom: 28,
+ left: 44,
+ right: 44,
+ textAlign: "center",
+ fontSize: 8,
+ color: MUTED,
+ },
+});
diff --git a/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-a4.pdf/route.ts b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-a4.pdf/route.ts
new file mode 100644
index 0000000..40829a7
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-a4.pdf/route.ts
@@ -0,0 +1,12 @@
+import { blankInvoicePdfResponse } from "../blank-invoice-pdf-response";
+
+/** Rendered once at build time and served as a static file. */
+export const dynamic = "force-static";
+
+/** The blank invoice template on A4 paper, linked from `/invoice-template-pdf`. */
+export function GET() {
+ return blankInvoicePdfResponse({
+ pageSize: "A4",
+ fileName: "blank-invoice-template-a4.pdf",
+ });
+}
diff --git a/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-letter.pdf/route.ts b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-letter.pdf/route.ts
new file mode 100644
index 0000000..72ba10a
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/invoice-template-pdf/blank-invoice-template-letter.pdf/route.ts
@@ -0,0 +1,12 @@
+import { blankInvoicePdfResponse } from "../blank-invoice-pdf-response";
+
+/** Rendered once at build time and served as a static file. */
+export const dynamic = "force-static";
+
+/** The blank invoice template on US Letter paper, linked from `/invoice-template-pdf`. */
+export function GET() {
+ return blankInvoicePdfResponse({
+ pageSize: "LETTER",
+ fileName: "blank-invoice-template-letter.pdf",
+ });
+}
diff --git a/src/app/(main)/(seo-landings)/proforma-invoice-generator/page.tsx b/src/app/(main)/(seo-landings)/proforma-invoice-generator/page.tsx
new file mode 100644
index 0000000..3f0cb1a
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/proforma-invoice-generator/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("proforma-invoice-generator");
+};
+
+export default function ProformaInvoiceGeneratorPage() {
+ return <SeoLandingRoutePage slug="proforma-invoice-generator" />;
+}
diff --git a/src/app/(main)/(seo-landings)/seo-landing-definitions.ts b/src/app/(main)/(seo-landings)/seo-landing-definitions.ts
index 334fc17..327c52c 100644
--- a/src/app/(main)/(seo-landings)/seo-landing-definitions.ts
+++ b/src/app/(main)/(seo-landings)/seo-landing-definitions.ts
@@ -1,3 +1,4 @@
+import type { RoughAnnotationType } from "@/components/rough-annotation";
import {
STATIC_ASSETS_URL,
VIDEO_DEMO_HERO_YOUTUBE_URL,
@@ -5,6 +6,7 @@ import {
VIDEO_MULTI_LANGUAGE_YOUTUBE_URL,
VIDEO_NORDIC_INVOICE_YOUTUBE_URL,
} from "@/config";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
export const SEO_LANDING_SLUGS = [
"invoice-generator-no-login",
@@ -14,6 +16,12 @@ export const SEO_LANDING_SLUGS = [
"multi-language-invoice-generator",
"swedish-invoice-generator",
"norwegian-invoice-generator",
+ "spanish-invoice-generator",
+ "german-invoice-generator",
+ "contractor-invoice-template",
+ "freelance-invoice-template",
+ "proforma-invoice-generator",
+ "export-invoice-format",
] as const;
export type SeoLandingSlug = (typeof SEO_LANDING_SLUGS)[number];
@@ -51,10 +59,43 @@ export interface SeoLandingDefinition {
};
hero: {
h1: string;
+ /**
+ * The hand-drawn mark drawn on one phrase of the h1 once the page loads.
+ *
+ * A phrase, so the mark points at the reason to read on (No Sign Up, Factura, SEK)
+ * rather than painting the whole heading. Only highlight and underline: they draw one
+ * stroke per line if the phrase wraps, where a box or circle around a wide word cuts
+ * through its corners. Each landing gets its own type and colour pairing (checked in
+ * `seo-landing-h1-marks.test.ts`).
+ */
+ h1Mark: {
+ /**
+ * Text inside `h1` to annotate, matched exactly.
+ *
+ * rough-notation inserts its SVG beside the phrase (before a highlight, after an
+ * underline), and that absolutely positioned SVG counts as a word break in the
+ * heading's accessible name. So a highlight's phrase must follow a space or open the
+ * heading, and an underline's must precede a space or end it; otherwise the name
+ * reads "Spanish ( Factura)". Hence "(Factura)" with its parentheses.
+ */
+ phrase: string;
+ type: Extract<RoughAnnotationType, "highlight" | "underline">;
+ /** Any CSS colour; highlights sit behind the text, so keep them light. */
+ color: string;
+ };
subheading: string;
bullets: string[];
ctaLabel: string;
ctaHref: string;
+ /**
+ * Files to download straight from the hero, under the CTA. For queries where the
+ * searcher wants a file rather than a tool ("invoice template pdf").
+ */
+ downloads?: {
+ /** Lead-in before the links, e.g. "Prefer a blank PDF?" */
+ label: string;
+ files: { label: string; href: string }[];
+ };
/**
* Shown in the hero, and used as the poster frame when {@link heroVideo} is set.
*/
@@ -99,9 +140,27 @@ export interface SeoLandingDefinition {
};
comparisonTable?: ComparisonTable;
faq: SeoFaqItem[];
+ /**
+ * Other landings this one links to, in a block under the FAQ.
+ *
+ * Before this the landings reached each other only through the footer list, which
+ * search engines weigh less than links in the body. Pick pages a reader of this one
+ * plausibly needs next, not a fixed set.
+ */
+ relatedSlugs: readonly SeoLandingSlug[];
}
-const DEFAULT_INVOICE_TEMPLATE_HREF = "/?template=default";
+/** The invoice app, opened on the visitor's last used template (default for new visitors). */
+const APP_HREF = "/";
+
+/**
+ * The blank, fillable invoice PDFs, rendered at build time by the route handlers under
+ * `invoice-template-pdf/`.
+ */
+const BLANK_INVOICE_PDF_HREFS = {
+ a4: "/invoice-template-pdf/blank-invoice-template-a4.pdf",
+ letter: "/invoice-template-pdf/blank-invoice-template-letter.pdf",
+} as const;
export const SEO_LANDING_DEFINITIONS = {
"invoice-generator-no-login": {
@@ -114,7 +173,13 @@ export const SEO_LANDING_DEFINITIONS = {
"invoice generator, free invoice generator, invoice generator tool, invoice maker, invoice builder, create invoice free, free bill generator, invoice generator no login, no signup invoice maker, free invoice forms, bill template, browser invoice generator, ad-free invoice generator",
},
hero: {
- h1: "Free Invoice Generator - No Login Required",
+ h1: "Free Invoice Generator - No Sign Up, No Login",
+ // yellow-300
+ h1Mark: {
+ phrase: "No Sign Up",
+ type: "highlight",
+ color: "rgb(253 224 71)",
+ },
subheading:
"Fill in the form, watch the PDF redraw beside it, then download the file. No account, no email, no credit card. The invoice is rendered on your own machine, so nothing you type is uploaded.",
bullets: [
@@ -125,7 +190,7 @@ export const SEO_LANDING_DEFINITIONS = {
"No ads and no tracking pixels",
],
ctaLabel: "Create and Download a PDF",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
heroVideo: {
embedUrl: VIDEO_DEMO_HERO_YOUTUBE_URL,
@@ -152,7 +217,7 @@ export const SEO_LANDING_DEFINITIONS = {
label: "Templates",
value: "A default layout and a Stripe-style one",
},
- { label: "Languages on the PDF", value: "12" },
+ { label: "Languages on the PDF", value: "13" },
{
label: "Currencies",
value: "122, picked separately from the language",
@@ -240,7 +305,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
{
feature: "Languages on the PDF",
- thisTool: "✅ 12",
+ thisTool: "✅ 13",
other: "⚠️ Usually one",
},
{
@@ -251,6 +316,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
],
},
+ relatedSlugs: [
+ "open-source-invoice-generator",
+ "invoice-template-pdf",
+ "freelance-invoice-template",
+ ],
faq: [
{
question: "Do I need to create an account?",
@@ -305,6 +375,12 @@ export const SEO_LANDING_DEFINITIONS = {
},
hero: {
h1: "Open-Source Invoice Generator - Free and Self-Hostable",
+ // emerald-500
+ h1Mark: {
+ phrase: "Open-Source",
+ type: "underline",
+ color: "rgb(16 185 129)",
+ },
subheading:
"The whole generator is on GitHub under AGPL-3.0. Use the hosted copy, fork it, or run it on your own server. Either way the PDF is rendered in the browser and no account is involved.",
bullets: [
@@ -315,7 +391,7 @@ export const SEO_LANDING_DEFINITIONS = {
"No account, no ads",
],
ctaLabel: "Create and Download a PDF",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
heroImage: `${STATIC_ASSETS_URL}/seo-content/str-tmp-v2.png`,
heroVideo: {
embedUrl: VIDEO_LIVE_PREVIEW_YOUTUBE_URL,
@@ -344,7 +420,7 @@ export const SEO_LANDING_DEFINITIONS = {
value: "Clone it, install with pnpm, deploy anywhere Next.js runs",
},
{ label: "Account required", value: "No" },
- { label: "Languages on the PDF", value: "12" },
+ { label: "Languages on the PDF", value: "13" },
{ label: "Currencies", value: "122" },
{ label: "Price", value: "Free, hosted and self-hosted alike" },
],
@@ -391,7 +467,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
],
comparisonTable: {
- heading: "Open source compared",
+ heading: "Open-source invoice software compared",
intro:
"Most invoicing tools are closed products with an export button. This compares what changes when the code is public.",
columnLabels: ["", "EasyInvoicePDF.com", "Closed invoicing tools"],
@@ -420,6 +496,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
],
},
+ relatedSlugs: [
+ "invoice-generator-no-login",
+ "multi-language-invoice-generator",
+ "stripe-invoice-alternative",
+ ],
faq: [
{
question: "Is it really open source?",
@@ -466,14 +547,20 @@ export const SEO_LANDING_DEFINITIONS = {
"stripe-invoice-alternative": {
slug: "stripe-invoice-alternative",
metadata: {
- title: "Free Stripe Invoice Alternative - PDF, No Account",
+ title: "Stripe Invoice Generator - Free, No Stripe Account",
description:
- "Need the invoice rather than the payment stack? Fill in a Stripe-style invoice, add your logo, and download the PDF. No Stripe account, no dashboard, free.",
+ "A free Stripe invoice generator for when you need the invoice, not the payment stack. Fill in the Stripe-style layout, add your logo, download the PDF.",
keywords:
- "stripe invoice alternative, invoice without stripe, create invoice without stripe, stripe style invoice template, invoice generator with logo, simple PDF invoice, invoice billing software, business billing software, wave accounting alternative, zoho billing alternative, ad-free invoicing",
+ "stripe invoice generator, stripe invoice pdf, stripe invoice alternative, invoice without stripe, create invoice without stripe, stripe style invoice template, invoice generator with logo, simple PDF invoice, invoice billing software, business billing software, wave accounting alternative, zoho billing alternative, ad-free invoicing",
},
hero: {
- h1: "Create a Stripe-Style Invoice Without Stripe",
+ h1: "Stripe Invoice Generator, No Stripe Account Needed",
+ // Stripe's own blurple
+ h1Mark: {
+ phrase: "No Stripe Account Needed",
+ type: "underline",
+ color: "rgb(99 91 255)",
+ },
subheading:
"The Stripe-style template is here as a layout you fill in and download. No payments account, no products to configure, no dashboard to learn. Add your logo, pick the currency, press Download PDF.",
bullets: [
@@ -484,7 +571,7 @@ export const SEO_LANDING_DEFINITIONS = {
"Free, with no signup",
],
ctaLabel: "Create a Stripe-Style Invoice",
- ctaHref: "/?template=stripe",
+ ctaHref: STRIPE_TEMPLATE_PATHNAME,
heroImage: `${STATIC_ASSETS_URL}/seo-content/stripe-template-v1.png`,
},
factsTable: {
@@ -508,7 +595,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
{ label: "Your logo", value: "JPEG, PNG or WebP, up to 3MB" },
{ label: "Currencies", value: "122" },
- { label: "Languages on the PDF", value: "12" },
+ { label: "Languages on the PDF", value: "13" },
{ label: "Price", value: "Free" },
],
},
@@ -587,6 +674,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid" },
],
},
+ relatedSlugs: [
+ "invoice-template-pdf",
+ "invoice-generator-no-login",
+ "proforma-invoice-generator",
+ ],
faq: [
{
question: "Do I need a Stripe account?",
@@ -633,14 +725,20 @@ export const SEO_LANDING_DEFINITIONS = {
"invoice-template-pdf": {
slug: "invoice-template-pdf",
metadata: {
- title: "Free Invoice Template - Fill It In, Download a PDF",
+ title: "Free Invoice Template PDF - Fill In and Download",
description:
- "A free invoice template that fills itself in. Type into the form, the PDF redraws beside it, download it. No Word formatting, no Google Docs table, no signup.",
+ "A free invoice template PDF. Fill it in online with the totals done for you, or download a blank fillable PDF in A4 or US Letter. No signup, no Word file.",
keywords:
- "free invoice template PDF, invoice template word, invoice format word, word document invoice template, invoice template google docs, bill template google docs, billing template google docs, invoice template canva, small business invoice template, bill template, billing template free, free sample invoice, free invoice example, printable invoice template, invoice PDF download",
+ "free invoice template PDF, blank invoice template pdf, fillable invoice template pdf, printable invoice template pdf, invoice template word, invoice format word, word document invoice template, invoice template google docs, bill template google docs, billing template google docs, invoice template canva, small business invoice template, bill template, billing template free, free sample invoice, free invoice example, printable invoice template, invoice PDF download",
},
hero: {
- h1: "Free Invoice Template - Fill It In and Download a PDF",
+ h1: "Free Invoice Template PDF You Fill In Online",
+ // rose-500
+ h1Mark: {
+ phrase: "Fill In Online",
+ type: "underline",
+ color: "rgb(244 63 94)",
+ },
subheading:
"A Word or Google Docs invoice template is a document you keep repairing. This one is a form: type into the fields, watch the PDF redraw beside them, and download it when it reads right.",
bullets: [
@@ -651,7 +749,17 @@ export const SEO_LANDING_DEFINITIONS = {
"Free, with no signup",
],
ctaLabel: "Fill In and Download a PDF",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
+ downloads: {
+ label: "Prefer a blank PDF to fill in or print?",
+ files: [
+ { label: "Download A4", href: BLANK_INVOICE_PDF_HREFS.a4 },
+ {
+ label: "Download US Letter",
+ href: BLANK_INVOICE_PDF_HREFS.letter,
+ },
+ ],
+ },
heroImage: `${STATIC_ASSETS_URL}/seo-content/def-tmp-v2.png`,
heroVideo: {
embedUrl: VIDEO_DEMO_HERO_YOUTUBE_URL,
@@ -666,6 +774,10 @@ export const SEO_LANDING_DEFINITIONS = {
heading: "The template at a glance",
rows: [
{ label: "What you get", value: "A PDF, generated in your browser" },
+ {
+ label: "Blank PDF",
+ value: "Fillable and printable, in A4 or US Letter",
+ },
{
label: "What you fill in",
value: "A web form, not a document you have to edit",
@@ -676,7 +788,7 @@ export const SEO_LANDING_DEFINITIONS = {
value: "A plain default one and a Stripe-style one",
},
{ label: "Your logo", value: "JPEG, PNG or WebP, up to 3MB" },
- { label: "Languages on the PDF", value: "12" },
+ { label: "Languages on the PDF", value: "13" },
{ label: "Currencies", value: "122" },
{
label: "Date formats",
@@ -727,6 +839,14 @@ export const SEO_LANDING_DEFINITIONS = {
"Hide the fields you do not use, so the PDF has no empty rows",
],
},
+ {
+ title: "A blank invoice template PDF, if you prefer one",
+ lead: "Some invoices are written by hand, or typed into a PDF reader. For those there is a blank template, in A4 and in US Letter.",
+ paragraphs: [
+ "Every field in it is a form field, so Acrobat, Preview or your browser lets you type straight into it. Each one also sits on a ruled line, so a printed copy works with a pen. It has room for ten line items, a subtotal, tax and total, payment details and notes.",
+ "What a blank PDF cannot do is the math. The subtotal, tax and total are yours to work out, which is where the online template above earns its keep.",
+ ],
+ },
{
title: "Built for the invoice you send a few times a month",
paragraphs: [
@@ -773,7 +893,7 @@ export const SEO_LANDING_DEFINITIONS = {
},
{
feature: "Languages on the document",
- thisTool: "✅ 12",
+ thisTool: "✅ 13",
other: "❌ Translate it yourself",
},
{
@@ -783,7 +903,17 @@ export const SEO_LANDING_DEFINITIONS = {
},
],
},
+ relatedSlugs: [
+ "freelance-invoice-template",
+ "contractor-invoice-template",
+ "proforma-invoice-generator",
+ ],
faq: [
+ {
+ question: "Can I download a blank invoice template PDF?",
+ answer:
+ "Yes, in A4 or US Letter, from the links at the top of the page. It is fillable, so you can type into it in any PDF reader, and printable, with ruled lines for writing by hand. It does not total anything for you; the online template does.",
+ },
{
question: "Is this better than a Word invoice template?",
answer:
@@ -836,12 +966,18 @@ export const SEO_LANDING_DEFINITIONS = {
metadata: {
title: "Multi-Language Invoice Generator - Free PDF, 13 Languages",
description:
- "Create a professional invoice in Swedish, Norwegian, German, Spanish, Brazilian Portuguese and eight more languages. Labels, dates and the amount in words are all localized. Free, no signup.",
+ "Create a professional invoice in 13 languages, from Swedish to Brazilian Portuguese. Labels, dates and the amount in words are all localized. Free, no signup.",
keywords:
- "multi language invoice generator, invoice in different languages, multilingual invoice template, swedish invoice generator, norwegian invoice generator, german invoice template, spanish invoice generator, brazilian portuguese invoice generator, invoice amount in words, foreign language invoice, international invoice PDF",
+ "multi language invoice generator, invoice in spanish, invoice in german, invoice in french, invoice in different languages, multilingual invoice template, swedish invoice generator, norwegian invoice generator, german invoice template, spanish invoice generator, brazilian portuguese invoice generator, invoice amount in words, foreign language invoice, international invoice PDF",
},
hero: {
h1: "Invoice Generator in 13 Languages - Free PDF",
+ // sky-200
+ h1Mark: {
+ phrase: "13 Languages",
+ type: "highlight",
+ color: "rgb(186 230 253)",
+ },
subheading:
"Pick a language and the whole invoice follows: every label, the date format, the tax wording and the amount written out in words. Free, in your browser, with no signup.",
bullets: [
@@ -852,7 +988,7 @@ export const SEO_LANDING_DEFINITIONS = {
"Free and open-source. No login.",
],
ctaLabel: "Invoice in Your Language",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
heroVideo: {
embedUrl: VIDEO_MULTI_LANGUAGE_YOUTUBE_URL,
@@ -919,8 +1055,22 @@ export const SEO_LANDING_DEFINITIONS = {
],
},
{
- title: "All 13 languages",
- lead: "English, Polski, Nederlands, Français, Deutsch, Italiano, Norsk bokmål, Português, Português (Brasil), Русский, Español, Svenska, Українська.",
+ title: "All 13 languages, and their word for invoice",
+ lead: "Each language titles the PDF with its own word for invoice. This is what the Stripe-style template prints at the top of the page:",
+ bullets: [
+ "English: Invoice",
+ "Spanish (Español): Factura",
+ "German (Deutsch): Rechnung",
+ "French (Français): Facture",
+ "Italian (Italiano): Fattura",
+ "Dutch (Nederlands): Factuur",
+ "Polish (Polski): Faktura",
+ "Swedish (Svenska): Faktura",
+ "Norwegian (Norsk bokmål): Faktura",
+ "Portuguese (Português), Portugal and Brazil: Fatura",
+ "Russian (Русский): Счет",
+ "Ukrainian (Українська): Рахунок",
+ ],
paragraphs: [
"Brazilian Portuguese is the most recent addition, and a separate entry rather than a spelling variant: it labels the tax number CNPJ/CPF instead of NIF, calls the tax Imposto and its rate Alíquota rather than IVA, and writes the total the way Brazil counts — um bilhão where Portugal says mil milhões.",
"The language of the PDF is independent of the language you use the app in, and of the currency. Invoice a German client in EUR while working in English, or send a Swedish invoice in USD.",
@@ -980,6 +1130,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Free", thisTool: "✅ Always", other: "⚠️ Paid plans" },
],
},
+ relatedSlugs: [
+ "spanish-invoice-generator",
+ "german-invoice-generator",
+ "swedish-invoice-generator",
+ ],
faq: [
{
question: "Which languages can I create an invoice in?",
@@ -1016,6 +1171,11 @@ export const SEO_LANDING_DEFINITIONS = {
answer:
"Yes. The generator is free and open-source, with no paid tier gating the languages. You can inspect the code on GitHub or host it yourself.",
},
+ {
+ question: "What is invoice in Spanish, German or French?",
+ answer:
+ "Factura in Spanish, Rechnung in German and Facture in French. Pick one of those as the invoice language and the PDF uses that word in its title, along with translated labels for every other field.",
+ },
{
question: "Can I send the same invoice in two languages?",
answer:
@@ -1030,10 +1190,12 @@ export const SEO_LANDING_DEFINITIONS = {
description:
"Create a Swedish invoice PDF with SEK amounts, moms wording and Swedish labels on every field. The total is written out in Swedish. Free, no account.",
keywords:
- "swedish invoice generator, invoice generator sweden, faktura mall, fakturamall gratis, swedish invoice template, invoice in SEK, moms invoice, swedish krona invoice, faktura pdf, invoice for swedish clients",
+ "swedish invoice generator, invoice svenska, faktura på engelska, invoice generator sweden, faktura mall, fakturamall gratis, swedish invoice template, invoice in SEK, moms invoice, swedish krona invoice, faktura pdf, invoice for swedish clients",
},
hero: {
h1: "Create a Swedish invoice in SEK",
+ // blue-600, from the Swedish flag
+ h1Mark: { phrase: "Swedish", type: "underline", color: "rgb(37 99 235)" },
subheading:
"Set the invoice language to Swedish and every printed label changes with it: the seller and buyer blocks, the moms wording, the dates, and the total written out in words. Set the currency to SEK for Swedish krona. Nothing to install, and no account to make.",
bullets: [
@@ -1043,7 +1205,7 @@ export const SEO_LANDING_DEFINITIONS = {
"Free and open source",
],
ctaLabel: "Create a Swedish Invoice",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
heroVideo: {
embedUrl: VIDEO_NORDIC_INVOICE_YOUTUBE_URL,
@@ -1113,6 +1275,21 @@ export const SEO_LANDING_DEFINITIONS = {
"An invoice issued on 17 December 2025 is dated 2025-12-17 on the default template and 17 december 2025 on the Stripe-style one. Twelve other formats sit in the dropdown if a client expects something else.",
],
},
+ {
+ title: "Swedish invoice terms in English",
+ lead: "Billing a client who does not read Swedish, or reading a Swedish invoice yourself? These are the labels the PDF uses, and their English equivalents:",
+ bullets: [
+ "Faktura: Invoice",
+ "Säljare and Köpare: Seller and Buyer",
+ "Moms: VAT, and Momsreg.nr: VAT number",
+ "Förfallodatum: Due date",
+ "Att betala: Amount to pay",
+ "Kontonummer: Account number",
+ ],
+ paragraphs: [
+ "Need the invoice in English instead, a faktura på engelska? Switch the invoice language to English and keep SEK as the currency. Nothing else changes.",
+ ],
+ },
{
title: "Create a Swedish invoice",
lead: "Four steps, and nothing to download:",
@@ -1158,6 +1335,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
],
},
+ relatedSlugs: [
+ "norwegian-invoice-generator",
+ "multi-language-invoice-generator",
+ "freelance-invoice-template",
+ ],
faq: [
{
question:
@@ -1165,6 +1347,17 @@ export const SEO_LANDING_DEFINITIONS = {
answer:
"Yes. Language and currency are separate settings, so Swedish wording works with any of the 122 currencies. Billing a German client in euros while keeping Swedish labels takes one dropdown.",
},
+ {
+ question: "What is invoice in Swedish?",
+ answer:
+ "Faktura. With Swedish selected, the PDF is titled Faktura and the invoice number is labelled Fakturanummer.",
+ },
+ {
+ question:
+ "Can I write the invoice in English for a Swedish client, or the other way round?",
+ answer:
+ "Yes. Language is one dropdown, so the same invoice can be downloaded in Swedish and in English. Amounts, items and dates stay exactly as you entered them.",
+ },
{
question: "Does the invoice say moms or VAT?",
answer:
@@ -1208,6 +1401,12 @@ export const SEO_LANDING_DEFINITIONS = {
},
hero: {
h1: "Create a Norwegian invoice in NOK",
+ // red-600, from the Norwegian flag
+ h1Mark: {
+ phrase: "Norwegian",
+ type: "underline",
+ color: "rgb(220 38 38)",
+ },
subheading:
"Set the invoice language to Norwegian and every printed label changes with it: the seller and buyer blocks, the MVA wording, the dates, and the total written out in words. Set the currency to NOK for Norwegian kroner. Nothing to install, and no account to make.",
bullets: [
@@ -1217,7 +1416,7 @@ export const SEO_LANDING_DEFINITIONS = {
"Free and open source",
],
ctaLabel: "Create a Norwegian Invoice",
- ctaHref: DEFAULT_INVOICE_TEMPLATE_HREF,
+ ctaHref: APP_HREF,
heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
heroVideo: {
embedUrl: VIDEO_NORDIC_INVOICE_YOUTUBE_URL,
@@ -1288,6 +1487,21 @@ export const SEO_LANDING_DEFINITIONS = {
"An invoice issued on 17 December 2025 reads 17. desember 2025 on the Stripe-style template, with the point after 17. The default template dates it 2025-12-17. Thirteen other formats sit in the dropdown.",
],
},
+ {
+ title: "Norwegian invoice terms in English",
+ lead: "Billing a client who does not read Norwegian, or reading a Norwegian invoice yourself? These are the labels the PDF uses, and their English equivalents:",
+ bullets: [
+ "Faktura: Invoice",
+ "Selger and Kjøper: Seller and Buyer",
+ "MVA: VAT, and Org.nr: Organisation number",
+ "Forfallsdato: Due date",
+ "Å betale: Amount to pay",
+ "Kontonummer: Account number",
+ ],
+ paragraphs: [
+ "Need the invoice in English instead? Switch the invoice language to English and keep NOK as the currency. Nothing else changes.",
+ ],
+ },
{
title: "Create a Norwegian invoice",
lead: "Four steps, and nothing to download:",
@@ -1337,6 +1551,11 @@ export const SEO_LANDING_DEFINITIONS = {
{ feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
],
},
+ relatedSlugs: [
+ "swedish-invoice-generator",
+ "multi-language-invoice-generator",
+ "freelance-invoice-template",
+ ],
faq: [
{
question:
@@ -1344,6 +1563,11 @@ export const SEO_LANDING_DEFINITIONS = {
answer:
"Yes. Language and currency are separate settings, so Norwegian wording works with any of the 122 currencies. Billing a Swedish client in SEK while keeping Norwegian labels takes one dropdown.",
},
+ {
+ question: "What is invoice in Norwegian?",
+ answer:
+ "Faktura. With Norwegian selected, the PDF is titled Faktura, and the line items, tax and totals use Bokmål labels.",
+ },
{
question: "Does the invoice say MVA or VAT?",
answer:
@@ -1376,4 +1600,1045 @@ export const SEO_LANDING_DEFINITIONS = {
},
],
},
+ "spanish-invoice-generator": {
+ slug: "spanish-invoice-generator",
+ metadata: {
+ title: "Invoice in Spanish - Free Factura Generator (PDF)",
+ description:
+ "Create an invoice in Spanish, a factura, with IVA wording and Spanish labels on every field. The total is written out in Spanish words. Free PDF, no signup.",
+ keywords:
+ "invoice in spanish, spanish invoice, spanish invoice template, how to say invoice in spanish, invoice in spanish translation, factura, factura en inglés, invoice en español, factura template, IVA invoice, bilingual invoice",
+ },
+ hero: {
+ h1: "Create an Invoice in Spanish (Factura)",
+ // orange-200
+ h1Mark: {
+ phrase: "(Factura)",
+ type: "highlight",
+ color: "rgb(254 215 170)",
+ },
+ subheading:
+ "Invoice in Spanish is factura. Set the invoice language to Spanish and every printed label changes with it: Vendedor and Comprador, IVA, the dates, and the total written out in Spanish words. Pick any currency. Nothing to install, and no account to make.",
+ bullets: [
+ "Spanish labels on every field of the PDF",
+ "IVA wording and the NIF/CIF tax number label",
+ "Total in words: mil doscientos treinta y cuatro",
+ "Free and open source",
+ ],
+ ctaLabel: "Create a Spanish Invoice",
+ ctaHref: APP_HREF,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
+ heroVideo: {
+ embedUrl: VIDEO_MULTI_LANGUAGE_YOUTUBE_URL,
+ title:
+ "EasyInvoicePDF: 10 languages and 100+ currencies support #invoice #oss #freelancelife",
+ description:
+ "A walkthrough of picking an invoice language and currency, and the PDF changing with them.",
+ uploadDate: "2026-09-08T16:36:13-07:00",
+ thumbnailUrl: "https://i.ytimg.com/vi/ITMeKohyz3I/maxresdefault.jpg",
+ },
+ },
+ factsTable: {
+ heading: "Spanish invoices at a glance",
+ rows: [
+ { label: "Invoice in Spanish", value: "Factura" },
+ { label: "Invoice language", value: "Spanish (Español)" },
+ { label: "Tax wording", value: "IVA, with Tipo IVA for the rate" },
+ { label: "Tax number label", value: "NIF/CIF, which you can rename" },
+ {
+ label: "Date on the invoice",
+ value:
+ "2025-12-17, or 17 de diciembre de 2025 on the Stripe-style template",
+ },
+ {
+ label: "Amounts",
+ value: "1.234,56, with a comma before the cents",
+ },
+ {
+ label: "Total in words",
+ value: "mil doscientos treinta y cuatro for 1234",
+ },
+ { label: "Account required", value: "No" },
+ ],
+ },
+ sections: [
+ {
+ title: "Spanish invoice terms in English",
+ lead: "Invoice in Spanish is factura, and an invoice in English is what a Spanish speaker means by factura en inglés. These are the labels the PDF prints, with their English equivalents:",
+ bullets: [
+ "Factura: Invoice, and Factura n.º: Invoice number",
+ "Vendedor and Comprador: Seller and Buyer",
+ "Fecha de emisión: Date of issue",
+ "Fecha de vencimiento: Due date",
+ "IVA: VAT, and NIF/CIF: Tax ID",
+ "Precio neto and Importe bruto: Net price and Gross amount",
+ "Total a pagar: Total to pay",
+ "Importe en letras: Amount in words",
+ "Forma de pago: Payment method",
+ ],
+ },
+ {
+ title: "What changes when you pick Spanish",
+ lead: "Choosing Spanish rewrites the PDF itself, not only the app around it. Each printed label comes from a Spanish translation rather than an English string with a Spanish title on top.",
+ paragraphs: [
+ "The tax column reads IVA, and the summary table gives the rate as Tipo IVA. If you bill under another name, such as IGIC in the Canary Islands or IVA with a Mexican RFC, rename the tax label and the tax number label, and the new wording appears everywhere they print.",
+ ],
+ },
+ {
+ title: "The total, written out in Spanish",
+ lead: "Spanish invoices often repeat the total in words, and the generator writes it the way Spanish counts.",
+ paragraphs: [
+ "1234 becomes mil doscientos treinta y cuatro. Note mil, never un mil, and the y that joins tens and units, as in treinta y cuatro.",
+ ],
+ },
+ {
+ title: "Spanish words, any currency",
+ showComparisonTable: true,
+ lead: "Currency is a separate setting, so a Spanish invoice can be billed in euros, Mexican pesos, US dollars or any of 122 currencies.",
+ paragraphs: [
+ "Amounts follow Spanish punctuation: a point between thousands and a comma before the cents, so 1.234,56. On the Stripe-style template the date reads 17 de diciembre de 2025.",
+ ],
+ },
+ {
+ title: "The same invoice in English and in Spanish",
+ lead: "Language is one dropdown, so a bilingual client can get both.",
+ paragraphs: [
+ "Download the Spanish PDF, switch the language to English and download again. The line items, amounts and dates stay exactly as you entered them; only the printed labels change.",
+ ],
+ },
+ {
+ title: "Create a Spanish invoice",
+ lead: "Four steps, and nothing to download:",
+ bullets: [
+ "Open the generator and set Invoice PDF Language to Spanish",
+ "Pick the currency your client pays in",
+ "Fill in your details and line items, watching the preview update",
+ "Download the PDF, or send your client a link to it",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "Spanish support compared",
+ intro:
+ "Many invoice tools translate their own interface and leave the document in English. This compares what reaches your client.",
+ columnLabels: [
+ "On the PDF",
+ "EasyInvoicePDF.com",
+ "Typical invoice tool",
+ ],
+ rows: [
+ {
+ feature: "Spanish labels",
+ thisTool: "✅ Every field",
+ other: "⚠️ Often partial",
+ },
+ {
+ feature: "IVA wording",
+ thisTool: "✅ Automatic",
+ other: "⚠️ Manual",
+ },
+ {
+ feature: "Total in Spanish words",
+ thisTool: "✅ Yes",
+ other: "❌ Rarely",
+ },
+ {
+ feature: "Spanish number format",
+ thisTool: "✅ 1.234,56",
+ other: "⚠️ Varies",
+ },
+ { feature: "Account required", thisTool: "❌ No", other: "✅ Usually" },
+ { feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
+ ],
+ },
+ relatedSlugs: [
+ "german-invoice-generator",
+ "multi-language-invoice-generator",
+ "freelance-invoice-template",
+ ],
+ faq: [
+ {
+ question: "How do you say invoice in Spanish?",
+ answer:
+ "Factura. With Spanish selected, the PDF is titled Factura and the number is labelled Factura n.º on the default template, or Número de factura on the Stripe-style one.",
+ },
+ {
+ question: "What is factura in English?",
+ answer:
+ "Invoice. To send a Spanish-speaking business an invoice in English, keep the language on English; to send it in Spanish, switch to Spanish. The content stays the same either way.",
+ },
+ {
+ question: "Does the invoice say IVA or VAT?",
+ answer:
+ "IVA. Picking Spanish sets the tax label to IVA on the line items and Tipo IVA in the summary. You can replace it with your own wording, such as IGIC, and it is used everywhere the tax appears.",
+ },
+ {
+ question: "Can I use it for Mexico or other Latin American countries?",
+ answer:
+ "For the wording, yes: rename NIF/CIF to RFC or your local tax ID and pick the currency. It produces a PDF, not a CFDI or any other government e-invoice, so check whether your invoices must be issued through one.",
+ },
+ {
+ question: "Do I need an account?",
+ answer:
+ "No. There is no signup and no email step. The PDF is built in your browser, so the invoice data never reaches a server.",
+ },
+ {
+ question: "Is this accounting software?",
+ answer:
+ "No. It produces invoice PDFs and does not file, track or reconcile anything, and it makes no compliance guarantees. Check the result against your own bookkeeping requirements.",
+ },
+ ],
+ },
+ "german-invoice-generator": {
+ slug: "german-invoice-generator",
+ metadata: {
+ title: "Invoice in German - Free Rechnung Generator (PDF)",
+ description:
+ "Create an invoice in German, a Rechnung, with MwSt. wording and German labels on every field. The total is written out in German. Free PDF, no signup.",
+ keywords:
+ "invoice in german, german invoice, german invoice template, invoice deutsch, rechnung englisch, rechnung auf englisch, englische rechnung vorlage, rechnungsvorlage englisch, MwSt invoice, kleinunternehmer rechnung englisch",
+ },
+ hero: {
+ h1: "Create an Invoice in German (Rechnung)",
+ // amber-500, the gold of the German flag
+ h1Mark: {
+ phrase: "(Rechnung)",
+ type: "underline",
+ color: "rgb(245 158 11)",
+ },
+ subheading:
+ "Invoice in German is Rechnung. Set the invoice language to German and every printed label changes with it: Verkäufer and Käufer, MwSt., the dates, and the total written out in German. Or keep it in English for a client abroad. Nothing to install, and no account to make.",
+ bullets: [
+ "German labels on every field of the PDF",
+ "MwSt. wording and the USt-IdNr label",
+ "Total in words: eintausendzweihundertvierunddreißig",
+ "Free and open source",
+ ],
+ ctaLabel: "Create a German Invoice",
+ ctaHref: APP_HREF,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
+ heroVideo: {
+ embedUrl: VIDEO_MULTI_LANGUAGE_YOUTUBE_URL,
+ title:
+ "EasyInvoicePDF: 10 languages and 100+ currencies support #invoice #oss #freelancelife",
+ description:
+ "A walkthrough of picking an invoice language and currency, and the PDF changing with them.",
+ uploadDate: "2026-09-08T16:36:13-07:00",
+ thumbnailUrl: "https://i.ytimg.com/vi/ITMeKohyz3I/maxresdefault.jpg",
+ },
+ },
+ factsTable: {
+ heading: "German invoices at a glance",
+ rows: [
+ { label: "Invoice in German", value: "Rechnung" },
+ { label: "Rechnung in English", value: "Invoice" },
+ { label: "Invoice language", value: "German (Deutsch)" },
+ { label: "Tax wording", value: "MwSt., with MwSt.-Satz for the rate" },
+ { label: "Tax number label", value: "USt-IdNr, which you can rename" },
+ {
+ label: "Date on the invoice",
+ value:
+ "2025-12-17, 17.12.2025 with DD.MM.YYYY, or 17. Dezember 2025 on the Stripe-style template",
+ },
+ {
+ label: "Total in words",
+ value: "eintausendzweihundertvierunddreißig for 1234",
+ },
+ { label: "Account required", value: "No" },
+ ],
+ },
+ sections: [
+ {
+ title: "German invoice terms in English",
+ lead: "Invoice in German is Rechnung, and Rechnung in English is invoice. These are the labels the PDF prints, with their English equivalents:",
+ bullets: [
+ "Rechnung: Invoice, and Rechnungsnummer: Invoice number",
+ "Verkäufer and Käufer: Seller and Buyer",
+ "Ausstellungsdatum: Date of issue",
+ "Leistungsdatum and Leistungszeitraum: Date and period of service",
+ "Fälligkeitsdatum: Due date",
+ "MwSt.: VAT, and USt-IdNr: VAT ID",
+ "Nettobetrag and Bruttobetrag: Net amount and Gross amount",
+ "Zu zahlen and Restbetrag: To pay and Balance due",
+ "Betrag in Worten: Amount in words",
+ ],
+ },
+ {
+ title: "Rechnung auf Englisch: the same invoice in English",
+ lead: "Billing a client outside Germany? Keep the invoice language on English and nothing else changes.",
+ paragraphs: [
+ "Every label prints in English, the currency stays whatever you set, and the total is written out in English words. Switch the language back to German and download again for a German-speaking client. The line items, amounts and dates stay exactly as you entered them.",
+ ],
+ },
+ {
+ title: "What a German invoice has to show",
+ lead: "German VAT law lists what an invoice must contain. The form has a field for each, and the German labels name them the way a German accountant expects:",
+ bullets: [
+ "Your full name and address, and your client's",
+ "Your Steuernummer or USt-IdNr",
+ "The date of issue and a unique, sequential invoice number",
+ "What you supplied, and how much of it",
+ "The date or period of the service",
+ "The net amount, the tax rate and the tax amount, or a note on why no tax is charged",
+ ],
+ paragraphs: [
+ "Check the result with your Steuerberater. German B2B invoicing is also moving to structured e-invoices, such as XRechnung and ZUGFeRD, in stages; a PDF from this tool is not one.",
+ ],
+ },
+ {
+ title: "Kleinunternehmer: an invoice without MwSt.",
+ lead: "Under the small business rule in § 19 UStG, no VAT is charged, and the invoice says so.",
+ paragraphs: [
+ "Hide the tax columns, or set the rate to 0, and add a note in the notes field that refers to § 19 UStG, for example: Gemäß § 19 UStG wird keine Umsatzsteuer berechnet. Check the exact wording with your Steuerberater.",
+ ],
+ },
+ {
+ title: "Dates and amounts the German way",
+ showComparisonTable: true,
+ lead: "German writes the day with a full stop after it, and the decimal with a comma.",
+ paragraphs: [
+ "On the Stripe-style template the date reads 17. Dezember 2025. On the default template, pick DD.MM.YYYY from the date format dropdown for 17.12.2025. Amounts follow German punctuation, so 1.234,56.",
+ ],
+ },
+ {
+ title: "Create a German invoice",
+ lead: "Four steps, and nothing to download:",
+ bullets: [
+ "Open the generator and set Invoice PDF Language to German",
+ "Set the currency, EUR for most German clients",
+ "Fill in your details and line items, watching the preview update",
+ "Download the PDF, or send your client a link to it",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "German support compared",
+ intro:
+ "Many invoice tools translate their own interface and leave the document in English. This compares what reaches your client.",
+ columnLabels: [
+ "On the PDF",
+ "EasyInvoicePDF.com",
+ "Typical invoice tool",
+ ],
+ rows: [
+ {
+ feature: "German labels",
+ thisTool: "✅ Every field",
+ other: "⚠️ Often partial",
+ },
+ {
+ feature: "MwSt. wording",
+ thisTool: "✅ Automatic",
+ other: "⚠️ Manual",
+ },
+ {
+ feature: "Total in German words",
+ thisTool: "✅ Yes",
+ other: "❌ Rarely",
+ },
+ {
+ feature: "Date with ordinal point",
+ thisTool: "✅ 17. Dezember",
+ other: "⚠️ Often dropped",
+ },
+ { feature: "Account required", thisTool: "❌ No", other: "✅ Usually" },
+ { feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
+ ],
+ },
+ relatedSlugs: [
+ "spanish-invoice-generator",
+ "multi-language-invoice-generator",
+ "freelance-invoice-template",
+ ],
+ faq: [
+ {
+ question: "What is invoice in German?",
+ answer:
+ "Rechnung. With German selected, the PDF is titled Rechnung and the number is labelled Rechnungsnummer.",
+ },
+ {
+ question: "What is Rechnung in English?",
+ answer:
+ "Invoice. To write a Rechnung auf Englisch, keep the invoice language on English; every label prints in English and the total is written out in English words.",
+ },
+ {
+ question: "Does the invoice say MwSt. or USt.?",
+ answer:
+ "MwSt. on the line items, and MwSt.-Satz for the rate in the summary. You can replace the label with USt. or any other wording, and it is used everywhere the tax appears.",
+ },
+ {
+ question: "Can I write a Kleinunternehmer invoice?",
+ answer:
+ "Yes. Hide the tax columns or set the rate to 0, and add the § 19 UStG note in the notes field. Check the exact wording with your Steuerberater.",
+ },
+ {
+ question: "Is this an XRechnung or ZUGFeRD e-invoice?",
+ answer:
+ "No. It produces a PDF. If your client or the law requires a structured e-invoice, you need a tool that issues one.",
+ },
+ {
+ question: "Do I need an account?",
+ answer:
+ "No. There is no signup and no email step. The PDF is built in your browser, so the invoice data never reaches a server.",
+ },
+ ],
+ },
+ "contractor-invoice-template": {
+ slug: "contractor-invoice-template",
+ metadata: {
+ title: "Free Contractor Invoice Template - PDF in USD",
+ description:
+ "A free independent contractor invoice template. Bill hours or a flat fee in US dollars, date it MM/DD/YYYY, and download the PDF. No signup, no Word file.",
+ keywords:
+ "contractor invoice template, independent contractor invoice template, invoice template for contractors, contractor invoice, independent contractor invoice, 1099 invoice template, 1099 contractor invoice template, hourly invoice template, contractor invoice pdf, free contractor invoice",
+ },
+ hero: {
+ h1: "Free Contractor Invoice Template",
+ // teal-500
+ h1Mark: {
+ phrase: "Contractor",
+ type: "underline",
+ color: "rgb(20 184 166)",
+ },
+ subheading:
+ "Bill a client for hours or a flat fee, in US dollars, on a PDF that looks the same in every inbox. Type into the form and the invoice redraws beside it. No account, no Word file to fight with, and nothing you type leaves your browser.",
+ bullets: [
+ "Hours × rate, totaled for you",
+ "USD amounts, formatted $1,234.56",
+ "US dates: 03/20/2026 or March 20, 2026",
+ "Sales tax columns you can hide",
+ "Free, no signup",
+ ],
+ ctaLabel: "Create a Contractor Invoice",
+ ctaHref: APP_HREF,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
+ },
+ factsTable: {
+ heading: "A US contractor invoice at a glance",
+ rows: [
+ { label: "Currency", value: "USD, printed as $1,234.56" },
+ {
+ label: "Date format",
+ value: "MM/DD/YYYY, M/D/YYYY or March 20, 2026",
+ },
+ {
+ label: "Hourly billing",
+ value: "Quantity is the hours, unit is hrs, price is the rate",
+ },
+ {
+ label: "Sales tax",
+ value: "Label it Sales Tax, set a rate, or hide the tax columns",
+ },
+ {
+ label: "Service period",
+ value: "Optional from and to dates for the work billed",
+ },
+ { label: "Account required", value: "No" },
+ { label: "Price", value: "Free, and the source is on GitHub" },
+ ],
+ },
+ sections: [
+ {
+ title: "What a contractor invoice needs",
+ lead: "A client's accounts payable team pays faster when nothing has to be asked twice. These are the fields the template gives you, each one a form input:",
+ bullets: [
+ "Your name or business name, address and email",
+ "The client's name and billing address",
+ "A unique invoice number, and the date you issued it",
+ "The dates the work covers, as a service period",
+ "Each line of work, with hours or quantity, rate and amount",
+ "The total due, the due date, and how to pay you",
+ ],
+ },
+ {
+ title: "Billing by the hour",
+ lead: "Hourly work maps straight onto the line items.",
+ paragraphs: [
+ "Put the hours in the quantity field, write hrs as the unit, and enter your hourly rate as the price. The line total and the invoice total update as you type, so 32.5 hours at $85 shows as $2,762.50 before you download anything.",
+ "A flat-fee project is a single line with a quantity of 1. Mix both on one invoice when a job had a fixed scope plus extra hours.",
+ ],
+ },
+ {
+ title: "Sales tax, only if you charge it",
+ lead: "Many services are not taxed, but the rules change from state to state.",
+ paragraphs: [
+ "The tax label defaults to VAT, which reads oddly on a US invoice. Rename it to Sales Tax and set the rate, or hide the tax columns entirely and the invoice shows plain amounts. Check your own state's rules before deciding.",
+ ],
+ },
+ {
+ title: "Keep your SSN off the invoice",
+ lead: "A client who files a 1099-NEC for you needs your taxpayer identification number, but the invoice is the wrong place for it.",
+ paragraphs: [
+ "Send that number once, on a W-9, and leave it off the invoice that gets forwarded around the client's office. The template's tax number field is optional and can be hidden. If you have an EIN and want it on the invoice, rename the label to EIN and fill it in.",
+ ],
+ },
+ {
+ title: "Dates the way US clients read them",
+ lead: "The default template dates invoices 2026-03-20. A US client will find a month-first date easier to read.",
+ paragraphs: [
+ "Pick MM/DD/YYYY, M/D/YYYY or MM-DD-YYYY from the date format dropdown, or switch to the Stripe-style template, which writes March 20, 2026 out of the box.",
+ ],
+ },
+ {
+ title: "Create a contractor invoice",
+ lead: "Four steps, and nothing to install:",
+ bullets: [
+ "Open the generator and set the currency to USD",
+ "Choose a US date format and rename the tax label, or hide it",
+ "Add your hours or fixed-fee lines, watching the preview update",
+ "Download the PDF, or send your client a link to it",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "Template file or generator",
+ intro:
+ "Most contractor invoice templates are a Word or spreadsheet file you download and edit. This compares that with filling in a form that writes the PDF for you.",
+ columnLabels: ["", "EasyInvoicePDF.com", "Word or Excel template"],
+ rows: [
+ {
+ feature: "Hours × rate math",
+ thisTool: "✅ Automatic",
+ other: "⚠️ Formulas you maintain",
+ },
+ {
+ feature: "Layout breaks when you edit",
+ thisTool: "✅ Never",
+ other: "⚠️ Often",
+ },
+ {
+ feature: "Saves your details for next time",
+ thisTool: "✅ In your browser",
+ other: "⚠️ Copy the file",
+ },
+ {
+ feature: "Works on a phone",
+ thisTool: "✅ Yes",
+ other: "❌ Rarely",
+ },
+ { feature: "Account required", thisTool: "❌ No", other: "❌ No" },
+ { feature: "Price", thisTool: "✅ Free", other: "✅ Usually free" },
+ ],
+ },
+ relatedSlugs: [
+ "freelance-invoice-template",
+ "invoice-template-pdf",
+ "invoice-generator-no-login",
+ ],
+ faq: [
+ {
+ question: "Is this a 1099 invoice template?",
+ answer:
+ "There is no special 1099 invoice. A 1099 contractor sends an ordinary invoice, and the client files a 1099-NEC from its own records at year end. This template covers the invoice; your tax ID goes to the client on a W-9.",
+ },
+ {
+ question: "Can I bill by the hour?",
+ answer:
+ "Yes. Enter the hours as the quantity, hrs as the unit and your rate as the price. Totals are calculated as you type.",
+ },
+ {
+ question: "Do I have to show sales tax?",
+ answer:
+ "No. You can rename the tax label to Sales Tax and set a rate, or hide the tax columns so the invoice shows plain amounts. Whether your service is taxable depends on your state.",
+ },
+ {
+ question: "Can I add my logo?",
+ answer:
+ "Yes. Both templates accept a JPEG, PNG or WebP logo, which sits at the top of the PDF.",
+ },
+ {
+ question: "Do I need an account?",
+ answer:
+ "No. There is no signup and no email step. Your details are saved in your own browser so the next invoice starts filled in.",
+ },
+ {
+ question: "Is this accounting software?",
+ answer:
+ "No. It produces invoice PDFs and does not file, track or reconcile anything, and it makes no tax or compliance guarantees. Check the result against your own requirements.",
+ },
+ ],
+ },
+ "freelance-invoice-template": {
+ slug: "freelance-invoice-template",
+ metadata: {
+ title: "Free Freelance Invoice Template - Fill In, Get a PDF",
+ description:
+ "A free freelance invoice template for designers, writers, developers and consultants. Bill in any of 122 currencies and download the PDF. No signup.",
+ keywords:
+ "freelance invoice template, freelancer invoice template, freelance invoice, freelance invoice generator, consulting invoice template, self employed invoice template, freelance writer invoice template, freelance designer invoice, freelance invoice pdf",
+ },
+ hero: {
+ h1: "Free Freelance Invoice Template",
+ // violet-200
+ h1Mark: {
+ phrase: "Freelance",
+ type: "highlight",
+ color: "rgb(221 214 254)",
+ },
+ subheading:
+ "Bill a client for a project, a retainer or a month of hours. Fill in the form, watch the PDF redraw beside it, and download it. Your details stay saved in your browser, so the next invoice takes a minute.",
+ bullets: [
+ "Your details saved for the next invoice",
+ "122 currencies, 13 invoice languages",
+ "Share a link instead of attaching a file",
+ "Free and open source, no signup",
+ ],
+ ctaLabel: "Create a Freelance Invoice",
+ ctaHref: APP_HREF,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/def-tmp-v2.png`,
+ },
+ factsTable: {
+ heading: "Freelance invoices at a glance",
+ rows: [
+ { label: "Currencies", value: "122, each with its own symbol" },
+ { label: "Invoice languages", value: "13" },
+ {
+ label: "Templates",
+ value: "A classic layout and a Stripe-style one",
+ },
+ { label: "Logo", value: "JPEG, PNG or WebP" },
+ {
+ label: "Payment details",
+ value: "Bank account, SWIFT/BIC, and an optional QR code",
+ },
+ { label: "Account required", value: "No" },
+ { label: "Price", value: "Free, and the source is on GitHub" },
+ ],
+ },
+ sections: [
+ {
+ title: "Built for repeat invoices",
+ lead: "A freelancer rarely sends one invoice. The tool keeps what stays the same between them.",
+ paragraphs: [
+ "Your own details, your clients and your last invoice are kept in your browser's storage. Open the page next month, bump the invoice number and the dates, and the rest is already there. Seller and buyer lists can be exported to a file and imported on another computer.",
+ ],
+ },
+ {
+ title: "What to put on a freelance invoice",
+ lead: "Clients pay faster when the invoice answers their questions before they ask:",
+ bullets: [
+ "A unique invoice number and the issue date",
+ "Your name, address and email, and the client's",
+ "One line per deliverable or per block of hours",
+ "The period the work covers",
+ "The due date and the total",
+ "How to pay: bank details, a payment link or a QR code",
+ ],
+ },
+ {
+ title: "Clients abroad",
+ lead: "Freelance work crosses borders more often than most small businesses do.",
+ paragraphs: [
+ "Currency and language are separate settings. Bill a German client in euros with German labels, or a US client in dollars in English, from the same saved profile. All 122 currencies keep their own symbol and number format.",
+ ],
+ },
+ {
+ title: "A link instead of an attachment",
+ lead: "Share a link to the finished invoice and the client opens the same PDF you see.",
+ paragraphs: [
+ "The invoice data is compressed into the link itself, so there is no copy of it on a server. Anyone with the link can view and download the PDF.",
+ ],
+ },
+ {
+ title: "Create a freelance invoice",
+ lead: "Four steps, and nothing to install:",
+ bullets: [
+ "Open the generator and fill in your details once",
+ "Pick the client's currency and invoice language",
+ "Add your line items, watching the preview update",
+ "Download the PDF, or send your client a link to it",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "Freelance invoicing options compared",
+ intro:
+ "Freelancers usually choose between a template file and an invoicing app with an account. This compares both with a free generator.",
+ columnLabels: ["", "EasyInvoicePDF.com", "Invoicing app"],
+ rows: [
+ { feature: "Account required", thisTool: "❌ No", other: "✅ Yes" },
+ {
+ feature: "Monthly fee",
+ thisTool: "✅ None",
+ other: "⚠️ Often, past a free tier",
+ },
+ {
+ feature: "Invoice data stored",
+ thisTool: "✅ Your browser only",
+ other: "⚠️ Vendor's servers",
+ },
+ {
+ feature: "Payment tracking",
+ thisTool: "❌ No",
+ other: "✅ Usually",
+ },
+ {
+ feature: "Languages on the PDF",
+ thisTool: "✅ 13",
+ other: "⚠️ Varies",
+ },
+ { feature: "Open source", thisTool: "✅ AGPL-3.0", other: "❌ Rarely" },
+ ],
+ },
+ relatedSlugs: [
+ "contractor-invoice-template",
+ "multi-language-invoice-generator",
+ "export-invoice-format",
+ ],
+ faq: [
+ {
+ question: "Is the freelance invoice template really free?",
+ answer:
+ "Yes. There is no paid plan, no watermark and no limit on invoices. The source code is on GitHub under AGPL-3.0.",
+ },
+ {
+ question: "Can I bill a client in another currency?",
+ answer:
+ "Yes. Pick any of the 122 currencies. The invoice language is a separate setting, so English labels work with euros, pounds or rupees.",
+ },
+ {
+ question: "Does it work as a consulting invoice template?",
+ answer:
+ "Yes. Consulting invoices have the same parts: a line per engagement or block of hours, a service period, payment terms and a total.",
+ },
+ {
+ question: "Where are my invoices stored?",
+ answer:
+ "In your own browser's storage. Nothing is uploaded, so clearing your browser data removes them. Download the PDFs you need to keep.",
+ },
+ {
+ question: "Can it track whether a client paid?",
+ answer:
+ "No. It produces the invoice PDF and nothing more. Payment tracking and reminders belong to accounting software.",
+ },
+ ],
+ },
+ "proforma-invoice-generator": {
+ slug: "proforma-invoice-generator",
+ metadata: {
+ title: "Free Proforma Invoice Generator - Download PDF",
+ description:
+ "Create a proforma invoice online and download it as a PDF. Title it Proforma Invoice, list the goods or services, quote the total. Free, no signup.",
+ keywords:
+ "proforma invoice, proforma invoice generator, proforma invoice format, proforma invoice template, proforma invoice pdf, pro forma invoice, proforma invoice format in word, create proforma invoice online, proforma invoice maker",
+ },
+ hero: {
+ h1: "Free Proforma Invoice Generator",
+ // pink-500
+ h1Mark: {
+ phrase: "Proforma",
+ type: "underline",
+ color: "rgb(236 72 153)",
+ },
+ subheading:
+ "Send a buyer the expected cost before the work starts or the goods ship. Rename the document to Proforma Invoice, fill in the lines, and download the PDF. No account, and the data stays in your browser.",
+ bullets: [
+ "Titled Proforma Invoice at the top of the PDF",
+ "Quote in any of 122 currencies",
+ "Taxes shown with your own label",
+ "Turn it into the final invoice later",
+ "Free, no signup",
+ ],
+ ctaLabel: "Create a Proforma Invoice",
+ ctaHref: STRIPE_TEMPLATE_PATHNAME,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/stripe-template-v1.png`,
+ },
+ factsTable: {
+ heading: "Proforma invoices at a glance",
+ rows: [
+ {
+ label: "What it is",
+ value: "A preliminary bill sent before a sale is final",
+ },
+ { label: "Legally a tax invoice", value: "No" },
+ {
+ label: "Common uses",
+ value: "Advance payments, import licences, letters of credit, quotes",
+ },
+ {
+ label: "Title on the PDF",
+ value: "Proforma Invoice, set in the invoice number label",
+ },
+ { label: "Currencies", value: "122" },
+ { label: "Account required", value: "No" },
+ ],
+ },
+ sections: [
+ {
+ title: "What a proforma invoice is",
+ lead: "A proforma invoice is a quote dressed as an invoice. It tells the buyer what they will be billed if they go ahead.",
+ paragraphs: [
+ "It lists the same things a final invoice does: seller, buyer, goods or services, quantities, prices, taxes and the total. The difference is its status. It does not record a completed sale, so it is not a tax invoice and is not entered in the books as revenue.",
+ "Buyers ask for one to approve a purchase internally, to pay an advance, to apply for an import licence, or to open a letter of credit with their bank.",
+ ],
+ },
+ {
+ title: "Proforma invoice format",
+ lead: "A proforma invoice usually carries:",
+ bullets: [
+ "The words Proforma Invoice, clearly at the top",
+ "A proforma number and the date of issue",
+ "Seller and buyer names, addresses and tax numbers",
+ "A description of each item, with quantity and unit price",
+ "Taxes, any shipping or other charges, and the total",
+ "Payment terms and how long the quote stays valid",
+ ],
+ },
+ {
+ title: "Making it say Proforma",
+ lead: "The generator does not have a separate proforma mode. Two fields do the job.",
+ paragraphs: [
+ "On the Stripe-style template, the invoice number label is the large title at the top of the page. Change it from Invoice to Proforma Invoice. On the default template, the same label sits beside the number, so Proforma Invoice No. reads naturally.",
+ "Use the header notes field for a line such as Valid for 30 days or Not a tax invoice. It prints under the title on both templates.",
+ ],
+ },
+ {
+ title: "From proforma to final invoice",
+ lead: "Once the buyer confirms, the numbers are already filled in.",
+ paragraphs: [
+ "Change the label back to Invoice, give it a number from your regular invoice series, update the dates, and download again. The proforma PDF you sent earlier stays as it was.",
+ ],
+ },
+ {
+ title: "Create a proforma invoice",
+ lead: "Four steps, and nothing to install:",
+ bullets: [
+ "Open the generator and set the invoice number label to Proforma Invoice",
+ "Pick the currency and add the goods or services",
+ "Note how long the quote is valid in the header notes",
+ "Download the PDF, or send your buyer a link to it",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "Proforma invoice vs tax invoice",
+ intro:
+ "The two documents look alike. What changes is when they are issued and what they prove.",
+ columnLabels: ["", "Proforma invoice", "Tax invoice"],
+ rows: [
+ {
+ feature: "Issued",
+ thisTool: "Before the sale",
+ other: "After the sale or delivery",
+ },
+ {
+ feature: "Payment demand",
+ thisTool: "No, an estimate",
+ other: "Yes",
+ },
+ {
+ feature: "Recorded as revenue",
+ thisTool: "No",
+ other: "Yes",
+ },
+ {
+ feature: "Tax can be claimed on it",
+ thisTool: "No",
+ other: "Yes, where rules allow",
+ },
+ {
+ feature: "Can change before final",
+ thisTool: "Yes",
+ other: "Only by credit note",
+ },
+ ],
+ },
+ relatedSlugs: [
+ "export-invoice-format",
+ "invoice-template-pdf",
+ "stripe-invoice-alternative",
+ ],
+ faq: [
+ {
+ question: "Is a proforma invoice a legal invoice?",
+ answer:
+ "No. It is a preliminary document. It does not record a completed sale, and in most countries, India included, the buyer cannot claim input tax on it.",
+ },
+ {
+ question: "Should a proforma invoice include tax?",
+ answer:
+ "Usually yes, so the buyer sees the full expected cost. Rename the tax label to match your tax, such as GST, VAT or Sales Tax, and set the rate.",
+ },
+ {
+ question: "Does a proforma invoice need its own number?",
+ answer:
+ "It is good practice. Many businesses use a separate series, such as PI-2026-001, so proformas never take a number from the tax invoice sequence.",
+ },
+ {
+ question: "Can I write the proforma in another language?",
+ answer:
+ "Yes. The PDF can be printed in 13 languages, and the label you type replaces the default title in any of them.",
+ },
+ {
+ question: "Do I need an account?",
+ answer:
+ "No. There is no signup and no email step. The PDF is built in your browser, so the quote never reaches a server.",
+ },
+ ],
+ },
+ "export-invoice-format": {
+ slug: "export-invoice-format",
+ metadata: {
+ title: "Export Invoice Format for Services, Free PDF",
+ description:
+ "Invoice a foreign client from India in USD, EUR or GBP. Add the LUT declaration, your GSTIN and SAC code, then download the PDF. Free, no signup.",
+ keywords:
+ "export invoice format, export invoice, export invoice template, lut invoice format, export invoice format under lut, export of services invoice format, invoice for foreign client, invoice in usd from india, freelancer invoice format india, invoice format for freelancers",
+ },
+ hero: {
+ h1: "Export Invoice Format for Services from India",
+ // orange-500, saffron
+ h1Mark: {
+ phrase: "for Services",
+ type: "underline",
+ color: "rgb(249 115 22)",
+ },
+ subheading:
+ "Bill a client abroad in their currency, with the LUT declaration and your GSTIN on the page. Fill in the form, watch the PDF redraw beside it, and download it. Free, no account, and nothing you type leaves your browser.",
+ bullets: [
+ "122 currencies, including USD, EUR and GBP",
+ "LUT declaration in the header notes",
+ "GSTIN and SAC code on the invoice",
+ "SWIFT/BIC and account number for the wire",
+ "Free and open source",
+ ],
+ ctaLabel: "Create an Export Invoice",
+ ctaHref: APP_HREF,
+ heroImage: `${STATIC_ASSETS_URL}/seo-content/default-template-v1.png`,
+ },
+ factsTable: {
+ heading: "An export of services invoice at a glance",
+ rows: [
+ {
+ label: "Currency",
+ value: "The client's, e.g. USD printed as $1,234.56",
+ },
+ {
+ label: "Tax under LUT",
+ value: "IGST at 0%, with the LUT declaration printed",
+ },
+ { label: "Your tax number", value: "GSTIN, in the seller block" },
+ { label: "SAC code", value: "In each line item's description" },
+ {
+ label: "Bank details",
+ value: "Account number or IBAN, and SWIFT/BIC",
+ },
+ { label: "Date format", value: "DD/MM/YYYY or any of 17 others" },
+ { label: "Account required", value: "No" },
+ ],
+ },
+ sections: [
+ {
+ title: "What an export invoice for services needs",
+ lead: "A GST-registered exporter of services generally shows these on the invoice. Confirm the details for your business with your CA.",
+ bullets: [
+ "Your name, address and GSTIN",
+ "A consecutive invoice number of up to 16 characters, and the date",
+ "The client's name and full address, including the country",
+ "A description of the service with its SAC code",
+ "The value, in the client's currency",
+ "IGST charged, or the LUT declaration if you export without paying it",
+ ],
+ },
+ {
+ title: "The LUT declaration",
+ lead: "Exporting under a Letter of Undertaking means no IGST is charged, and the invoice has to say why.",
+ paragraphs: [
+ "Put the declaration in the header notes field, for example: Supply meant for export under Letter of Undertaking without payment of integrated tax. Add your LUT reference number on the next line. The header notes print near the top of the invoice on both templates.",
+ "Rename the tax label to IGST and set the rate to 0, or hide the tax columns and let the declaration speak for itself.",
+ ],
+ },
+ {
+ title: "GSTIN and SAC codes",
+ lead: "The generator has no India-specific fields, but its labels are yours to rename.",
+ paragraphs: [
+ "Rename the seller's tax number label to GSTIN and enter your number. There is no separate SAC column, so write the code at the start or end of each line description, for example: Software development services (SAC 998314).",
+ ],
+ },
+ {
+ title: "Getting paid from abroad",
+ lead: "A wire from a foreign client needs exact bank details.",
+ paragraphs: [
+ "Fill in your account number and SWIFT/BIC in the seller block. If you take payment through a link, such as PayPal or Wise, put it in the QR code field. The QR code prints on the invoice, and the client's phone opens the link.",
+ ],
+ },
+ {
+ title: "What it does not do",
+ lead: "Better to know before you start:",
+ bullets: [
+ "Rupee amounts use 1,234,567 grouping, not lakh and crore",
+ "The amount in words counts in thousands and millions",
+ "There are no separate CGST and SGST columns for domestic invoices",
+ "No e-invoice IRN or GST portal filing",
+ ],
+ },
+ ],
+ comparisonTable: {
+ heading: "Export invoice options compared",
+ intro:
+ "Freelancers in India usually invoice foreign clients from a Word or Excel format, or from GST billing software. This compares those with a free generator.",
+ columnLabels: ["", "EasyInvoicePDF.com", "GST billing software"],
+ rows: [
+ { feature: "Account required", thisTool: "❌ No", other: "✅ Yes" },
+ {
+ feature: "Invoice in USD, EUR, GBP",
+ thisTool: "✅ 122 currencies",
+ other: "⚠️ Often paid plans",
+ },
+ {
+ feature: "LUT declaration",
+ thisTool: "✅ Header notes",
+ other: "✅ Built in",
+ },
+ {
+ feature: "CGST/SGST split",
+ thisTool: "❌ No",
+ other: "✅ Yes",
+ },
+ {
+ feature: "E-invoice IRN",
+ thisTool: "❌ No",
+ other: "⚠️ Some",
+ },
+ { feature: "Price", thisTool: "✅ Free", other: "⚠️ Paid plans" },
+ ],
+ },
+ relatedSlugs: [
+ "proforma-invoice-generator",
+ "freelance-invoice-template",
+ "multi-language-invoice-generator",
+ ],
+ faq: [
+ {
+ question: "Should an export invoice be in rupees or dollars?",
+ answer:
+ "Most freelancers bill in the client's currency, such as USD, and record the rupee value in their books at the exchange rate. Set the invoice currency to whatever the contract says.",
+ },
+ {
+ question: "Do I charge GST to a foreign client?",
+ answer:
+ "Export of services is zero-rated. You either export under an LUT and charge no IGST, or pay IGST and claim a refund. Most freelancers file an LUT. Check your case with your CA.",
+ },
+ {
+ question: "Where does the LUT declaration go?",
+ answer:
+ "In the header notes field, which prints near the top of the invoice. Add your LUT reference number there too.",
+ },
+ {
+ question: "Can I use this for domestic GST invoices?",
+ answer:
+ "Only for a single tax line, such as IGST on an interstate sale. There are no separate CGST and SGST columns, so an intrastate invoice is better made in GST billing software.",
+ },
+ {
+ question: "Is this a commercial invoice for shipping goods?",
+ answer:
+ "It can list goods, but it has no fields for HS codes, ports, Incoterms or package weights, which customs paperwork needs. It is built for invoicing services.",
+ },
+ {
+ question: "Is this accounting software?",
+ answer:
+ "No. It produces invoice PDFs and does not file, track or reconcile anything, and it makes no compliance guarantees. Check the result against GST rules with your CA.",
+ },
+ ],
+ },
} as const satisfies Record<SeoLandingSlug, SeoLandingDefinition>;
diff --git a/src/app/(main)/(seo-landings)/seo-landing-footer-links.ts b/src/app/(main)/(seo-landings)/seo-landing-footer-links.ts
index db1be02..df9d056 100644
--- a/src/app/(main)/(seo-landings)/seo-landing-footer-links.ts
+++ b/src/app/(main)/(seo-landings)/seo-landing-footer-links.ts
@@ -1,5 +1,26 @@
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
import type { SeoLandingSlug } from "./seo-landing-definitions";
+/**
+ * Footer links to routes of the invoice app itself, listed before the landings.
+ *
+ * `/stripe-template` is the page meant to rank for "Stripe invoice template"; a link to it
+ * from every page, with that phrase as the anchor, is the strongest internal signal we can
+ * give it. The `stripe-invoice-alternative` landing below targets "Stripe invoice
+ * generator" instead (the "without Stripe" wording it started with had no search volume),
+ * so the two do not compete for the same query.
+ */
+export const APP_FOOTER_SOLUTION_LINKS = [
+ {
+ href: STRIPE_TEMPLATE_PATHNAME,
+ label: "Free Stripe Invoice Template",
+ },
+] as const satisfies {
+ href: string;
+ label: string;
+}[];
+
/**
* Anchor text for the landing links in the site footer.
*
@@ -10,7 +31,7 @@ import type { SeoLandingSlug } from "./seo-landing-definitions";
export const SEO_FOOTER_SOLUTION_LINKS = [
{
slug: "invoice-generator-no-login",
- label: "Free Invoice Generator - No Login Required",
+ label: "Free Invoice Generator - No Sign Up, No Login",
},
{
slug: "open-source-invoice-generator",
@@ -18,15 +39,15 @@ export const SEO_FOOTER_SOLUTION_LINKS = [
},
{
slug: "stripe-invoice-alternative",
- label: "Create a Stripe-Style Invoice Without Stripe",
+ label: "Stripe Invoice Generator, No Stripe Account Needed",
},
{
slug: "invoice-template-pdf",
- label: "Free Invoice Template - Fill It In and Download a PDF",
+ label: "Free Invoice Template PDF You Fill In Online",
},
{
slug: "multi-language-invoice-generator",
- label: "Invoice Generator in 12 Languages - Free PDF",
+ label: "Invoice Generator in 13 Languages - Free PDF",
},
{
slug: "swedish-invoice-generator",
@@ -36,6 +57,30 @@ export const SEO_FOOTER_SOLUTION_LINKS = [
slug: "norwegian-invoice-generator",
label: "Norwegian Invoice Generator - Free PDF in NOK",
},
+ {
+ slug: "spanish-invoice-generator",
+ label: "Invoice in Spanish - Free Factura Generator",
+ },
+ {
+ slug: "german-invoice-generator",
+ label: "Invoice in German - Free Rechnung Generator",
+ },
+ {
+ slug: "contractor-invoice-template",
+ label: "Free Contractor Invoice Template",
+ },
+ {
+ slug: "freelance-invoice-template",
+ label: "Free Freelance Invoice Template",
+ },
+ {
+ slug: "proforma-invoice-generator",
+ label: "Free Proforma Invoice Generator",
+ },
+ {
+ slug: "export-invoice-format",
+ label: "Export Invoice Format for Services from India",
+ },
] as const satisfies {
slug: SeoLandingSlug;
label: string;
diff --git a/src/app/(main)/(seo-landings)/spanish-invoice-generator/page.tsx b/src/app/(main)/(seo-landings)/spanish-invoice-generator/page.tsx
new file mode 100644
index 0000000..0a9289c
--- /dev/null
+++ b/src/app/(main)/(seo-landings)/spanish-invoice-generator/page.tsx
@@ -0,0 +1,12 @@
+import {
+ buildSeoLandingMetadata,
+ SeoLandingRoutePage,
+} from "@/app/(main)/(seo-landings)/seo-landing-route";
+
+export const generateMetadata = () => {
+ return buildSeoLandingMetadata("spanish-invoice-generator");
+};
+
+export default function SpanishInvoiceGeneratorPage() {
+ return <SeoLandingRoutePage slug="spanish-invoice-generator" />;
+}
diff --git a/src/app/(main)/changelog/build-changelog-json-ld.ts b/src/app/(main)/changelog/build-changelog-json-ld.ts
index 9f48d47..9e38ebc 100644
--- a/src/app/(main)/changelog/build-changelog-json-ld.ts
+++ b/src/app/(main)/changelog/build-changelog-json-ld.ts
@@ -60,10 +60,13 @@ export function buildChangelogIndexJsonLdGraph(
},
},
buildOrganization(),
- buildBreadcrumbList(CHANGELOG_INDEX_URL, [
- { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
- { name: "Changelog" },
- ]),
+ buildBreadcrumbList({
+ pageUrl: CHANGELOG_INDEX_URL,
+ items: [
+ { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
+ { name: "Changelog" },
+ ],
+ }),
],
};
}
@@ -117,11 +120,14 @@ export function buildChangelogPostJsonLdGraph(entry: ChangelogEntry): Graph {
},
},
buildOrganization(),
- buildBreadcrumbList(pageUrl, [
- { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
- { name: "Changelog", item: CHANGELOG_INDEX_URL },
- { name: title },
- ]),
+ buildBreadcrumbList({
+ pageUrl,
+ items: [
+ { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
+ { name: "Changelog", item: CHANGELOG_INDEX_URL },
+ { name: title },
+ ],
+ }),
],
};
}
diff --git a/src/app/(main)/changelog/components/changelog-author-byline.tsx b/src/app/(main)/changelog/components/changelog-author-byline.tsx
index f453539..299d92c 100644
--- a/src/app/(main)/changelog/components/changelog-author-byline.tsx
+++ b/src/app/(main)/changelog/components/changelog-author-byline.tsx
@@ -37,7 +37,7 @@ export function ChangelogAuthorByline() {
<span className="text-sm text-slate-500 dark:text-neutral-400">
Founder,{" "}
<Link
- href="/?template=default"
+ href="/"
className="text-slate-500 no-underline hover:underline hover:underline-offset-2 dark:text-neutral-400"
>
{" "}
diff --git a/src/app/(main)/changelog/content/faster-pdf-preview-and-mobile-polish.mdx b/src/app/(main)/changelog/content/faster-pdf-preview-and-mobile-polish.mdx
index d0e86bd..e737485 100644
--- a/src/app/(main)/changelog/content/faster-pdf-preview-and-mobile-polish.mdx
+++ b/src/app/(main)/changelog/content/faster-pdf-preview-and-mobile-polish.mdx
@@ -1,8 +1,7 @@
export const metadata = {
- title:
- "EasyInvoicePDF v1.0.4 - Faster PDF preview, redesigned mobile tabs, and a fix for missing characters in PDFs",
+ title: "EasyInvoicePDF v1.0.4 - Faster PDF Preview, Mobile Polish",
description:
- "The invoice PDF is now generated once and shared across the page, mobile tabs were redesigned with a sliding indicator, dates in the form match the PDF language, and PDFs no longer drop the first characters of labels.",
+ "The PDF is generated once and shared across the page, mobile tabs were redesigned, form dates match the PDF language, and labels keep their first characters.",
date: "2026-09-04",
version: "1.0.4",
type: "minor",
diff --git a/src/app/(main)/changelog/content/number-format-and-brazilian-portuguese.mdx b/src/app/(main)/changelog/content/number-format-and-brazilian-portuguese.mdx
index fb905c7..7febd63 100644
--- a/src/app/(main)/changelog/content/number-format-and-brazilian-portuguese.mdx
+++ b/src/app/(main)/changelog/content/number-format-and-brazilian-portuguese.mdx
@@ -1,8 +1,7 @@
export const metadata = {
- title:
- "EasyInvoicePDF v1.0.5 - Number format setting, Brazilian Portuguese invoices, and large amounts that fit their columns",
+ title: "EasyInvoicePDF v1.0.5 - Number Formats, Brazilian Portuguese",
description:
- "Choose how amounts are punctuated independently of the invoice language, write invoices in Brazilian Portuguese, and large amounts now wrap inside their column instead of running over the next one.",
+ "Set how amounts are punctuated apart from the invoice language, write invoices in Brazilian Portuguese, and large amounts now wrap inside their column.",
date: "2026-09-24",
version: "1.0.5",
type: "minor",
diff --git a/src/app/(main)/changelog/content/qr-codes-and-improvements.mdx b/src/app/(main)/changelog/content/qr-codes-and-improvements.mdx
index 2f2bfba..b01f389 100644
--- a/src/app/(main)/changelog/content/qr-codes-and-improvements.mdx
+++ b/src/app/(main)/changelog/content/qr-codes-and-improvements.mdx
@@ -1,6 +1,5 @@
export const metadata = {
- title:
- "EasyInvoicePDF v1.0.2 - QR Code Support, Logo Upload for the Default Invoice Template and Many More",
+ title: "EasyInvoicePDF v1.0.2 - QR Codes and Logos on Invoices",
description:
"QR code generation for invoices, logo upload for the default template, searchable currency combobox, and improved multi-page PDF support",
date: "2026-03-10",
diff --git a/src/app/(main)/changelog/content/seller-buyer-improvements.mdx b/src/app/(main)/changelog/content/seller-buyer-improvements.mdx
index 4cf44c3..e773859 100644
--- a/src/app/(main)/changelog/content/seller-buyer-improvements.mdx
+++ b/src/app/(main)/changelog/content/seller-buyer-improvements.mdx
@@ -1,6 +1,5 @@
export const metadata = {
- title:
- "EasyInvoicePDF v1.0.3 - Email visibility toggle for seller and buyer, reworked seller/buyer sections, confirm dialog to discard changes, UX improvements",
+ title: "EasyInvoicePDF v1.0.3 - Seller and Buyer Improvements",
description:
"Email visibility toggle for seller/buyer sections, reworked form layouts with locked-state banners, ConfirmDiscardDialog, and auto-scroll on mobile",
date: "2026-03-29",
diff --git a/src/app/(main)/changelog/content/stripe-pdf-template.mdx b/src/app/(main)/changelog/content/stripe-pdf-template.mdx
index fb59f75..e0eab34 100644
--- a/src/app/(main)/changelog/content/stripe-pdf-template.mdx
+++ b/src/app/(main)/changelog/content/stripe-pdf-template.mdx
@@ -1,8 +1,7 @@
export const metadata = {
- title:
- "EasyInvoicePDF v1.0.1 - Customizable Tax/VAT Labels & Major Improvements",
+ title: "EasyInvoicePDF v1.0.1 - Custom Tax Labels and Improvements",
description:
- "Customizable tax and VAT labels, per-language tax labels, stronger VAT validation, localization updates, PDF performance, e2e and CI improvements, and bug fixes.",
+ "Customizable tax and VAT labels, per-language tax labels, stronger VAT validation, localization updates, faster PDFs, and bug fixes.",
date: "2026-01-12",
version: "1.0.1",
type: "minor",
diff --git a/src/app/(main)/founder/build-founder-json-ld.ts b/src/app/(main)/founder/build-founder-json-ld.ts
index 27a99fd..68c8288 100644
--- a/src/app/(main)/founder/build-founder-json-ld.ts
+++ b/src/app/(main)/founder/build-founder-json-ld.ts
@@ -38,10 +38,13 @@ export function buildFounderJsonLdGraph(): Graph {
"@id": JSON_LD_IDS.person,
},
},
- buildBreadcrumbList(pageUrl, [
- { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
- { name: "Founder" },
- ]),
+ buildBreadcrumbList({
+ pageUrl,
+ items: [
+ { name: "Start Invoicing", item: `${PROD_WEBSITE_URL}/` },
+ { name: "Founder" },
+ ],
+ }),
],
};
}
diff --git a/src/app/(main)/how-it-works/build-how-it-works-json-ld.ts b/src/app/(main)/how-it-works/build-how-it-works-json-ld.ts
index 2c84d1e..e10f547 100644
--- a/src/app/(main)/how-it-works/build-how-it-works-json-ld.ts
+++ b/src/app/(main)/how-it-works/build-how-it-works-json-ld.ts
@@ -63,10 +63,13 @@ export function buildHowItWorksJsonLd(baseUrl = PROD_WEBSITE_URL): Graph {
itemListElement: videoItems,
},
},
- buildBreadcrumbList(pageUrl, [
- { name: "Start Invoicing", item: `${baseUrl}/` },
- { name: "How it works" },
- ]),
+ buildBreadcrumbList({
+ pageUrl,
+ items: [
+ { name: "Start Invoicing", item: `${baseUrl}/` },
+ { name: "How it works" },
+ ],
+ }),
],
};
}
diff --git a/src/app/[locale]/about/about-json-ld-graph.ts b/src/app/[locale]/about/about-json-ld-graph.ts
index c241a15..901d1f1 100644
--- a/src/app/[locale]/about/about-json-ld-graph.ts
+++ b/src/app/[locale]/about/about-json-ld-graph.ts
@@ -70,10 +70,10 @@ export function buildAboutJsonLdGraph(
"@id": faqUrl,
mainEntity: faqEntities,
},
- buildBreadcrumbList(pageUrl, [
- { name: homeLabel, item: `${baseUrl}/` },
- { name: aboutLabel },
- ]),
+ buildBreadcrumbList({
+ pageUrl,
+ items: [{ name: homeLabel, item: `${baseUrl}/` }, { name: aboutLabel }],
+ }),
],
};
}
diff --git a/src/app/[locale]/about/components/about-footer.tsx b/src/app/[locale]/about/components/about-footer.tsx
index d1043f5..82f6930 100644
--- a/src/app/[locale]/about/components/about-footer.tsx
+++ b/src/app/[locale]/about/components/about-footer.tsx
@@ -50,7 +50,7 @@ export function AboutFooter() {
heading={t("footer.headings.product")}
links={[
{
- href: "/?template=default",
+ href: "/",
label: t("footer.links.invoiceGenerator"),
},
{
diff --git a/src/app/__tests__/robots.test.ts b/src/app/__tests__/robots.test.ts
new file mode 100644
index 0000000..e515f43
--- /dev/null
+++ b/src/app/__tests__/robots.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it } from "vitest";
+
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
+
+import robots from "../robots";
+
+/**
+ * Shared invoice links carry the whole invoice (names, addresses, amounts) in `?data=`,
+ * in every shape the app produces or used to produce.
+ */
+const SHARED_INVOICE_URLS = [
+ "/?data=abc",
+ "/?template=default&data=abc",
+ "/?data=abc&template=default",
+ "/?utm_source=newsletter&template=default&data=abc",
+ // legacy links, from before the Stripe template had its own route
+ "/?template=stripe&data=abc",
+ `${STRIPE_TEMPLATE_PATHNAME}?data=abc`,
+ `${STRIPE_TEMPLATE_PATHNAME}?utm_source=newsletter&data=abc`,
+] as const;
+
+/** The invoice app itself, which should be crawled. */
+const APP_URLS = [
+ "/",
+ "/?template=default",
+ "/?utm_source=newsletter",
+ STRIPE_TEMPLATE_PATHNAME,
+ `${STRIPE_TEMPLATE_PATHNAME}?utm_source=newsletter`,
+] as const;
+
+describe("robots.txt", () => {
+ const rules = getRulesForAllCrawlers();
+
+ it.each(SHARED_INVOICE_URLS)(
+ "disallows the shared invoice link %s",
+ (url) => {
+ expect(isAllowedByRobotsTxt({ rules, url })).toBe(false);
+ },
+ );
+
+ it.each(APP_URLS)("allows the invoice app at %s", (url) => {
+ expect(isAllowedByRobotsTxt({ rules, url })).toBe(true);
+ });
+});
+
+describe("isAllowedByRobotsTxt (the matcher these tests rely on)", () => {
+ it("lets the longest matching rule win, and allow win a tie", () => {
+ expect(
+ isAllowedByRobotsTxt({
+ rules: { allow: ["/page"], disallow: ["/page?*secret=*"] },
+ url: "/page?secret=1",
+ }),
+ ).toBe(false);
+
+ expect(
+ isAllowedByRobotsTxt({
+ rules: { allow: ["/page?a=1"], disallow: ["/page?*"] },
+ url: "/page?a=1",
+ }),
+ ).toBe(true);
+
+ expect(
+ isAllowedByRobotsTxt({
+ rules: { allow: ["/page"], disallow: ["/page"] },
+ url: "/page",
+ }),
+ ).toBe(true);
+ });
+
+ it("supports `*` wildcards and the `$` end anchor", () => {
+ const rules = { allow: [], disallow: ["/*.ico$"] };
+
+ expect(isAllowedByRobotsTxt({ rules, url: "/favicon.ico" })).toBe(false);
+ expect(isAllowedByRobotsTxt({ rules, url: "/favicon.ico?v=2" })).toBe(true);
+ });
+
+ it("allows what no rule matches", () => {
+ expect(
+ isAllowedByRobotsTxt({
+ rules: { allow: [], disallow: ["/private"] },
+ url: "/public",
+ }),
+ ).toBe(true);
+ });
+});
+
+interface RobotsRules {
+ allow: readonly string[];
+ disallow: readonly string[];
+}
+
+/** The rules `robots()` publishes for `User-agent: *`. */
+function getRulesForAllCrawlers(): RobotsRules {
+ const { rules } = robots();
+ const rule = (Array.isArray(rules) ? rules : [rules]).find(
+ ({ userAgent }) => {
+ return userAgent === "*";
+ },
+ );
+
+ if (!rule) {
+ throw new Error("robots.txt has no `User-agent: *` group");
+ }
+
+ return {
+ allow: toArray(rule.allow),
+ disallow: toArray(rule.disallow),
+ };
+}
+
+function toArray(value: string | string[] | undefined): string[] {
+ if (value === undefined) {
+ return [];
+ }
+
+ return Array.isArray(value) ? value : [value];
+}
+
+interface IsAllowedByRobotsTxtParams {
+ rules: RobotsRules;
+ /** Path plus query string, e.g. `/?data=abc`. */
+ url: string;
+}
+
+/**
+ * Whether a crawler may fetch `url`, following Google's reading of robots.txt
+ * (https://developers.google.com/search/docs/crawling-indexing/robots/robots_txt):
+ * rules match from the start of the path and query, `*` matches any run of characters
+ * and a trailing `$` anchors the end; of the matching rules the longest one wins, and
+ * `allow` wins a tie. A URL no rule matches is allowed.
+ *
+ * @returns `true` when the URL may be crawled.
+ */
+function isAllowedByRobotsTxt({
+ rules,
+ url,
+}: IsAllowedByRobotsTxtParams): boolean {
+ const longestAllow = longestMatchingRule({ patterns: rules.allow, url });
+ const longestDisallow = longestMatchingRule({
+ patterns: rules.disallow,
+ url,
+ });
+
+ return longestAllow >= longestDisallow;
+}
+
+interface LongestMatchingRuleParams {
+ patterns: readonly string[];
+ url: string;
+}
+
+/** @returns The length of the longest pattern matching `url`, or `-1` when none does. */
+function longestMatchingRule({ patterns, url }: LongestMatchingRuleParams) {
+ return Math.max(
+ -1,
+ ...patterns
+ .filter((pattern) => {
+ return robotsPatternToRegExp(pattern).test(url);
+ })
+ .map((pattern) => {
+ return pattern.length;
+ }),
+ );
+}
+
+function robotsPatternToRegExp(pattern: string) {
+ const isAnchored = pattern.endsWith("$");
+ const body = isAnchored ? pattern.slice(0, -1) : pattern;
+
+ const source = body
+ .split("*")
+ .map((part) => {
+ return part.replaceAll(/[.+?^${}()|[\]\\]/g, String.raw`\$&`);
+ })
+ .join(".*");
+
+ return new RegExp(`^${source}${isAnchored ? "$" : ""}`);
+}
diff --git a/src/app/api/generate-invoice/generate-invoice.ts b/src/app/api/generate-invoice/generate-invoice.ts
index 006e151..88a078c 100644
--- a/src/app/api/generate-invoice/generate-invoice.ts
+++ b/src/app/api/generate-invoice/generate-invoice.ts
@@ -5,6 +5,7 @@ import type { Attachment, CreateEmailResponse } from "resend";
import { invoiceSchema, type InvoiceData } from "@/app/schema";
import type { InvoiceFolderResult } from "@/lib/google-drive";
+import { buildInvoiceAppUrl } from "@/utils/invoice-app-url";
import { compressInvoiceData } from "@/utils/url-compression";
/**
@@ -288,7 +289,10 @@ export async function generateInvoice(
const compressedKeys = compressInvoiceData(newInvoiceDataValidated);
const compressedJson = JSON.stringify(compressedKeys);
const compressedData = compressToEncodedURIComponent(compressedJson);
- const invoiceUrl = `https://easyinvoicepdf.com/?template=${newInvoiceDataValidated.template}&data=${compressedData}`;
+ const invoiceUrl = `https://easyinvoicepdf.com${buildInvoiceAppUrl({
+ template: newInvoiceDataValidated.template,
+ searchParams: new URLSearchParams({ data: compressedData }),
+ })}`;
const monthAndYear = now.format("MMMM YYYY");
const invoiceNumberValue = englishInvoiceData?.invoiceNumberObject?.value;
diff --git a/src/app/robots.ts b/src/app/robots.ts
index 26d981f..8440984 100644
--- a/src/app/robots.ts
+++ b/src/app/robots.ts
@@ -1,6 +1,7 @@
import { type MetadataRoute } from "next";
import { APP_URL } from "@/config";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
import { SUPPORTED_I18N_LOCALES } from "./schema";
@@ -18,6 +19,8 @@ export default function robots(): MetadataRoute.Robots {
}),
// Allow template parameter URLs
"/?template=*",
+ // Allow the Stripe template variant of the app
+ STRIPE_TEMPLATE_PATHNAME,
// Allow changelog pages
"/changelog",
"/changelog/*",
@@ -38,6 +41,7 @@ export default function robots(): MetadataRoute.Robots {
"/?*data=*",
"/?template=*&data=*",
"/?data=*&template=*",
+ `${STRIPE_TEMPLATE_PATHNAME}?*data=*`,
// Disallow subscription confirmation pages with and without tokens
"/confirm-subscription",
"/confirm-subscription?*",
diff --git a/src/app/sitemap.ts b/src/app/sitemap.ts
index 5967aae..2ca2e0c 100644
--- a/src/app/sitemap.ts
+++ b/src/app/sitemap.ts
@@ -2,6 +2,7 @@ import { type MetadataRoute } from "next";
import { SEO_LANDING_SLUGS } from "@/app/(main)/(seo-landings)/seo-landing-definitions";
import { APP_URL } from "@/config";
+import { STRIPE_TEMPLATE_PATHNAME } from "@/utils/invoice-app-url";
import { getChangelogEntries } from "./(main)/changelog/utils";
import { SUPPORTED_I18N_LOCALES } from "./schema";
@@ -21,7 +22,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
},
// Stripe invoice template variant of the main app page
{
- url: `${APP_URL}/?template=stripe`,
+ url: `${APP_URL}${STRIPE_TEMPLATE_PATHNAME}`,
lastModified,
changeFrequency: "daily",
priority: 1,
diff --git a/src/components/rough-annotation.tsx b/src/components/rough-annotation.tsx
index 3c6097f..95af179 100644
--- a/src/components/rough-annotation.tsx
+++ b/src/components/rough-annotation.tsx
@@ -64,6 +64,12 @@ export function RoughAnnotation({
timeout = window.setTimeout(
() => {
annotation.show();
+ // The SVG is decoration, so keep it out of the accessibility tree. `show()` has
+ // just inserted it. (Hiding it does not stop it counting as a word break in the
+ // parent's accessible name: see `h1Mark.phrase` in the SEO landing definitions.)
+ element.parentElement
+ ?.querySelector(":scope > svg.rough-annotation")
+ ?.setAttribute("aria-hidden", "true");
},
reduceMotion ? 0 : delayMs,
);
diff --git a/src/components/track-click.tsx b/src/components/track-click.tsx
new file mode 100644
index 0000000..ae32bee
--- /dev/null
+++ b/src/components/track-click.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
+
+/**
+ * Sends an Umami event when anything inside it is clicked, leaving the click itself alone.
+ *
+ * For server components, which cannot pass an `onClick`: wrap a link in it, and the
+ * click bubbles up here after the link has done its job. Unlike Umami's `data-umami-event`
+ * attributes, nothing is intercepted. On an `<a>`, the tracker would cancel the click and
+ * re-navigate with `location.href` once its request settled: a next/link lost client-side
+ * navigation, and a `download` link opened its file in place of the page.
+ *
+ * `display: contents`, so the wrapper adds no box and the layout is as if it were absent.
+ * Keyboard activation (Enter on a link) is a click event too, so it is tracked the same.
+ */
+export function TrackClick({
+ event,
+ data,
+ children,
+}: {
+ /** Event name as it appears in the Umami dashboard, snake_case like the others. */
+ event: string;
+ /** Event properties sent with it. */
+ data?: Record<string, string>;
+ children: React.ReactNode;
+}) {
+ return (
+ // oxlint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events -- not interactive itself: it only observes clicks bubbling up from the link inside, which handles the keyboard
+ <span
+ className="contents"
+ onClick={() => {
+ umamiTrackEvent(event, { data });
+ }}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/src/config.ts b/src/config.ts
index 3eaf9ed..daedbf7 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -149,7 +149,7 @@ export const HOW_IT_WORKS_VIDEOS = [
title: "How to customize number formatting",
shortTitle: "Number formatting",
description:
- "Choose how amounts are written, like 1,234.56 or 1.234,56, and create invoices in Brazilian Portuguese.",
+ "Pick the thousands and decimal separators, like 10,000.00 or 10.000,00.",
embedUrl: YOUTUBE_VIDEO_HOW_TO_CUSTOMIZE_NUMBER_FORMAT,
watchUrl: "https://www.youtube.com/watch?v=hZM2DYXo63k",
uploadDate: "2026-09-24T05:17:16-07:00",
diff --git a/src/contexts/device-context.tsx b/src/contexts/device-context.tsx
index 5708ddb..4068453 100644
--- a/src/contexts/device-context.tsx
+++ b/src/contexts/device-context.tsx
@@ -1,9 +1,14 @@
"use client";
-import { createContext, useContext, useEffect, useState } from "react";
+import { createContext, useContext, useSyncExternalStore } from "react";
import { useIsDesktop } from "@/hooks/use-media-query";
-import type { InAppInfo } from "@/lib/check-device.server";
+import {
+ detectDevice,
+ SERVER_DEVICE_INFO,
+ type DeviceInfo,
+ type InAppInfo,
+} from "@/lib/detect-device";
interface DeviceContextType {
isDesktop: boolean;
@@ -27,47 +32,80 @@ export function useDeviceContext() {
return context;
}
+/**
+ * Provides the device detected from the browser's user agent.
+ *
+ * The invoice app is prerendered, so there is no request to read the user agent from on
+ * the server: the prerendered HTML assumes a desktop (`SERVER_DEVICE_INFO`) and the real
+ * values take over right after hydration.
+ */
+export function UserAgentDeviceContextProvider({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const deviceInfo = useSyncExternalStore(
+ subscribeToUserAgent,
+ getClientDeviceInfo,
+ getServerDeviceInfo,
+ );
+
+ return (
+ <DeviceContextProvider {...deviceInfo}>{children}</DeviceContextProvider>
+ );
+}
+
export function DeviceContextProvider({
children,
isDesktop,
isAndroid,
isMobile,
inAppInfo,
-}: Omit<DeviceContextType, "isUADesktop"> & { children: React.ReactNode }) {
- // we use this to show either desktop or mobile (tabs) UI
- const [isDesktopClient, setIsDesktopClient] = useState(isDesktop);
-
- // we use this when generating the invoice link, to show navigagor.share or copy to clipboard
- const [isUADesktop] = useState(isDesktop);
-
- // Check media query on client side as an additional check
+}: DeviceInfo & { children: React.ReactNode }) {
+ // Check media query on client side as an additional check, we use this to show
+ // either desktop or mobile (tabs) UI. `undefined` until it has been read in an effect.
const isMediaQueryDesktop = useIsDesktop();
- /**
- * Update the client state if the media query is defined
- * This is to ensure that the client state is always up to date, we use this to show either desktop or mobile (tabs) UI
- */
- useEffect(() => {
- if (isMediaQueryDesktop !== undefined) {
- // eslint-disable-next-line react-hooks/set-state-in-effect, react-you-might-not-need-an-effect/no-derived-state
- setIsDesktopClient(isMediaQueryDesktop);
- }
- }, [isMediaQueryDesktop]);
-
return (
<DeviceContext.Provider
value={{
- isDesktop: isDesktopClient,
+ isDesktop: isMediaQueryDesktop ?? isDesktop,
isAndroid,
isMobile,
inAppInfo,
/**
* we use this when generating the invoice link, to show navigagor.share or copy to clipboard
*/
- isUADesktop,
+ isUADesktop: isDesktop,
}}
>
{children}
</DeviceContext.Provider>
);
}
+
+/** The user agent never changes during the lifetime of the page. */
+function subscribeToUserAgent() {
+ return () => {
+ // nothing to unsubscribe from
+ };
+}
+
+let clientDeviceInfo: DeviceInfo | null = null;
+
+/**
+ * `useSyncExternalStore` compares snapshots by identity, so the result is computed once
+ * and reused rather than returning a fresh object on every render.
+ */
+function getClientDeviceInfo() {
+ clientDeviceInfo ??= detectDevice({
+ userAgent: navigator.userAgent,
+ maxTouchPoints: navigator.maxTouchPoints ?? 0,
+ });
+
+ return clientDeviceInfo;
+}
+
+function getServerDeviceInfo() {
+ return SERVER_DEVICE_INFO;
+}
diff --git a/src/lib/__tests__/detect-device.test.ts b/src/lib/__tests__/detect-device.test.ts
new file mode 100644
index 0000000..db81b9e
--- /dev/null
+++ b/src/lib/__tests__/detect-device.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+
+import { detectDevice } from "../detect-device";
+
+const USER_AGENTS = {
+ macChrome:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
+ windowsEdge:
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0",
+ iPhoneSafari:
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1",
+ iPadSafari:
+ "Mozilla/5.0 (iPad; CPU OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1",
+ // iPadOS 13+ asks for the desktop site by default and sends a Mac user agent
+ iPadDesktopMode:
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15",
+ androidPhoneChrome:
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Mobile Safari/537.36",
+ androidTabletChrome:
+ "Mozilla/5.0 (Linux; Android 14; SM-X710) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
+ androidWebView:
+ "Mozilla/5.0 (Linux; Android 14; Pixel 8 Build/AP2A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/140.0.0.0 Mobile Safari/537.36",
+ iPhoneInstagram:
+ "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 350.0.0.0.0",
+} as const;
+
+describe("detectDevice", () => {
+ it("classifies desktop browsers", () => {
+ for (const userAgent of [USER_AGENTS.macChrome, USER_AGENTS.windowsEdge]) {
+ expect(detectDevice({ userAgent, maxTouchPoints: 0 })).toEqual({
+ isDesktop: true,
+ isAndroid: false,
+ isMobile: false,
+ inAppInfo: { isInApp: false, name: null },
+ });
+ }
+ });
+
+ it("classifies phones", () => {
+ expect(
+ detectDevice({ userAgent: USER_AGENTS.iPhoneSafari, maxTouchPoints: 5 }),
+ ).toMatchObject({ isDesktop: false, isMobile: true, isAndroid: false });
+
+ expect(
+ detectDevice({
+ userAgent: USER_AGENTS.androidPhoneChrome,
+ maxTouchPoints: 5,
+ }),
+ ).toMatchObject({ isDesktop: false, isMobile: true, isAndroid: true });
+ });
+
+ it("classifies tablets as neither desktop nor mobile", () => {
+ for (const userAgent of [
+ USER_AGENTS.iPadSafari,
+ USER_AGENTS.iPadDesktopMode,
+ USER_AGENTS.androidTabletChrome,
+ ]) {
+ expect(detectDevice({ userAgent, maxTouchPoints: 5 })).toMatchObject({
+ isDesktop: false,
+ isMobile: false,
+ });
+ }
+ });
+
+ it("detects in-app browsers", () => {
+ expect(
+ detectDevice({
+ userAgent: USER_AGENTS.iPhoneInstagram,
+ maxTouchPoints: 5,
+ }).inAppInfo,
+ ).toEqual({ isInApp: true, name: "Instagram" });
+
+ expect(
+ detectDevice({ userAgent: USER_AGENTS.androidWebView, maxTouchPoints: 5 })
+ .inAppInfo,
+ ).toEqual({ isInApp: true, name: "Android WebView" });
+ });
+});
diff --git a/src/lib/check-device.server.ts b/src/lib/check-device.server.ts
deleted file mode 100644
index 62116f8..0000000
--- a/src/lib/check-device.server.ts
+++ /dev/null
@@ -1,356 +0,0 @@
-"use server";
-
-import { headers } from "next/headers";
-import { UAParser } from "ua-parser-js";
-
-export interface InAppInfo {
- isInApp: boolean;
- name: string | null;
-}
-
-type HeadersList = Awaited<ReturnType<typeof headers>>;
-
-/**
- * Simplified in-app browser detection with detailed app identification
- */
-function detectInAppBrowser(ua: string, headers: HeadersList) {
- const s = ua.toLowerCase();
-
- // Helper functions
- function has(token: string): boolean {
- return s.includes(token);
- }
-
- function ios(): boolean {
- return /iphone|ipad|ipod/.test(s);
- }
-
- // Check for app-specific headers first (most reliable)
- const xRequestedWith = headers.get("x-requested-with") || "";
- const headerDetectors = [
- {
- name: "Instagram",
- test: () => {
- return xRequestedWith.includes("com.instagram.android");
- },
- },
- {
- name: "Facebook",
- test: () => {
- return xRequestedWith.includes("com.facebook.katana");
- },
- },
- {
- name: "Facebook Messenger",
- test: () => {
- return xRequestedWith.includes("com.facebook.orca");
- },
- },
- {
- name: "Twitter/X",
- test: () => {
- return xRequestedWith.includes("com.twitter.android");
- },
- },
- {
- name: "TikTok",
- test: () => {
- return (
- xRequestedWith.includes("com.zhiliaoapp.musically") ||
- xRequestedWith.includes("com.ss.android.ugc.trill")
- );
- },
- },
- {
- name: "WhatsApp",
- test: () => {
- return xRequestedWith.includes("com.whatsapp");
- },
- },
- {
- name: "WeChat",
- test: () => {
- return xRequestedWith.includes("com.tencent.mm");
- },
- },
- {
- name: "LINE",
- test: () => {
- return xRequestedWith.includes("jp.naver.line.android");
- },
- },
- {
- name: "Telegram",
- test: () => {
- return (
- xRequestedWith.includes("org.telegram.messenger") ||
- xRequestedWith.includes("org.telegram.plus") ||
- xRequestedWith.includes("org.telegram.btelegram") ||
- xRequestedWith.includes("org.thunderdog.challegram") ||
- xRequestedWith.includes("nekox.messenger") ||
- xRequestedWith.includes("org.telegram.mdgram") ||
- xRequestedWith.includes("it.owlgram.android")
- );
- },
- },
- {
- name: "Gmail",
- test: () => {
- return xRequestedWith.includes("com.google.android.gm");
- },
- },
- {
- name: "Google App",
- test: () => {
- return xRequestedWith.includes(
- "com.google.android.googlequicksearchbox",
- );
- },
- },
- {
- name: "Chrome Custom Tab",
- test: () => {
- return (
- xRequestedWith.includes("com.android.chrome") ||
- xRequestedWith.includes("com.chrome.beta") ||
- xRequestedWith.includes("com.chrome.canary") ||
- xRequestedWith.includes("com.chrome.dev") ||
- xRequestedWith.includes("org.chromium.chrome")
- );
- },
- },
- {
- name: "LinkedIn",
- test: () => {
- return xRequestedWith.includes("com.linkedin.android");
- },
- },
- ];
-
- // Check headers first (most reliable)
- for (const detector of headerDetectors) {
- try {
- if (detector.test()) return { isInApp: true, name: detector.name };
- } catch {
- // ignore failing tests
- }
- }
-
- // User agent detectors (fallback)
- const uaDetectors = [
- {
- name: "Facebook",
- test: () => {
- return has("fbav") || has("fban") || has("fb_iab");
- },
- },
- {
- name: "Instagram",
- test: () => {
- return has("instagram");
- },
- },
- {
- name: "Facebook Messenger",
- test: () => {
- // iOS Messenger: [FBAN/MessengerForiOS;
- return (
- has("fban/messengerforio") ||
- has("messengerforio") ||
- // Android Messenger: [FB_IAB/MESSENGER;
- has("fb_iab/messenger") ||
- // Fallback patterns
- (has("messenger") && (has("fban") || has("fb_iab")))
- );
- },
- },
- {
- name: "WhatsApp",
- test: () => {
- return has("whatsapp");
- },
- },
- {
- name: "Telegram",
- test: () => {
- return (
- has("telegram") ||
- has("tgwebview") ||
- has("telegrambot-like") ||
- has("tgbot") ||
- has("telegram-") ||
- // Bot user agents
- has("telegrambot") ||
- // Version-specific patterns
- has("telegram/") ||
- // iOS specific patterns
- (ios() && (has("telegram") || has("tg/"))) ||
- // Android specific patterns
- (has("android") && has("tg"))
- );
- },
- },
- {
- name: "Twitter/X",
- test: () => {
- return has("twitter") || has("x-client");
- },
- },
- {
- name: "LinkedIn",
- test: () => {
- return has("linkedinapp");
- },
- },
- {
- name: "Pinterest",
- test: () => {
- return has("pinterest");
- },
- },
- {
- name: "Reddit",
- test: () => {
- return has("reddit");
- },
- },
- {
- name: "Snapchat",
- test: () => {
- return has("snapchat");
- },
- },
- {
- name: "TikTok",
- test: () => {
- return has("tiktok") || has("com.zhiliaoapp");
- },
- },
- {
- name: "WeChat",
- test: () => {
- return has("micromessenger");
- },
- },
- {
- name: "LINE",
- test: () => {
- return has("line/");
- },
- },
- {
- name: "QQ",
- test: () => {
- return has("qq/");
- },
- },
- {
- name: "Gmail",
- test: () => {
- return has("gmail");
- },
- },
- {
- name: "Google App",
- test: () => {
- return has("gsa/") || has("googleapp");
- },
- },
- {
- name: "Discord",
- test: () => {
- return has("discord");
- },
- },
- {
- name: "YouTube",
- test: () => {
- return has("youtube");
- },
- },
- {
- name: "Android WebView",
- test: () => {
- return has("wv") && has("android");
- },
- },
- {
- name: "iOS WebView",
- test: () => {
- return (
- ios() &&
- has("applewebkit") &&
- !has("safari") &&
- !has("crios") &&
- !has("fxios") &&
- !has("edgios")
- );
- },
- },
- {
- name: "Generic WebView",
- test: () => {
- return (
- (has("android") && has("webview")) ||
- (has("mobile safari") && !has("safari"))
- );
- },
- },
- ];
-
- // Test user agent patterns
- for (const detector of uaDetectors) {
- try {
- if (detector.test()) return { isInApp: true, name: detector.name };
- } catch {
- // ignore failing tests
- }
- }
-
- return { isInApp: false, name: null };
-}
-
-/**
- * Check the device type based on the user agent
- * @warning **Should only be used on server side**
- */
-export const checkDeviceUserAgent = async () => {
- if (typeof process === "undefined") {
- throw new TypeError(
- "[Server method] you are importing a server-only module outside of server",
- );
- }
-
- const headersList = await headers();
- const ua = headersList.get("user-agent");
-
- const parser = new UAParser(ua || "");
-
- const device = parser.getDevice();
- const os = parser.getOS();
-
- // Detect tablets specifically
- const isTablet =
- device.type === "tablet" ||
- // iPad on iOS 13+ reports as desktop
- (os.name === "iOS" && !ua?.includes("iPhone") && !ua?.includes("iPod"));
-
- // Detect mobile phones
- const isMobile = device.type === "mobile";
-
- // Detect Android specifically
- const isAndroid = os.name === "Android";
-
- // Detect in-app browsers/WebViews with detailed app identification
- const inAppInfo = detectInAppBrowser(ua || "", headersList);
-
- // Desktop is when it's neither tablet nor mobile
- const isDesktop = !isTablet && !isMobile;
-
- return {
- isDesktop,
- isAndroid,
- isMobile,
- inAppInfo, // Include detailed in-app browser information
- };
-};
diff --git a/src/lib/detect-device.ts b/src/lib/detect-device.ts
new file mode 100644
index 0000000..c570fa3
--- /dev/null
+++ b/src/lib/detect-device.ts
@@ -0,0 +1,270 @@
+/**
+ * Device and in-app-browser detection from the user agent, run in the browser.
+ *
+ * This used to run on the server from the request headers, which made `/` render per
+ * request. It is a pure function of `navigator` now, so the invoice app can be
+ * prerendered. Like `src/utils/browser-support.ts` it is hand-rolled rather than
+ * built on `ua-parser-js`: all we need is phone / tablet / desktop, and that is a
+ * handful of regexes instead of ~7 kB gzip of parser in the client bundle.
+ */
+
+export interface InAppInfo {
+ isInApp: boolean;
+ name: string | null;
+}
+
+export interface DeviceInfo {
+ /** Neither a phone nor a tablet. */
+ isDesktop: boolean;
+ isAndroid: boolean;
+ /** A phone (tablets are neither `isMobile` nor `isDesktop`). */
+ isMobile: boolean;
+ inAppInfo: InAppInfo;
+}
+
+interface DetectDeviceParams {
+ /** `navigator.userAgent`. */
+ userAgent: string;
+ /**
+ * `navigator.maxTouchPoints`. iPadOS 13+ sends a desktop Safari (Macintosh) user
+ * agent by default, and a touch screen is the only way to tell it apart from a Mac.
+ */
+ maxTouchPoints: number;
+}
+
+/**
+ * What the server (and the first client render, before hydration settles) assumes:
+ * a desktop browser that is not an in-app WebView. It only decides what the prerendered
+ * HTML looks like, and that is the CSS-responsive loading skeleton either way.
+ */
+export const SERVER_DEVICE_INFO: DeviceInfo = {
+ isDesktop: true,
+ isAndroid: false,
+ isMobile: false,
+ inAppInfo: { isInApp: false, name: null },
+};
+
+/**
+ * Classifies the current device from its user agent.
+ *
+ * @returns Whether the device is a desktop, a phone or neither (a tablet), whether it
+ * runs Android, and which in-app browser, if any, the page is open in.
+ */
+export function detectDevice({
+ userAgent,
+ maxTouchPoints,
+}: DetectDeviceParams): DeviceInfo {
+ const ua = userAgent.toLowerCase();
+
+ const isAndroid = ua.includes("android");
+ const isIPad =
+ ua.includes("ipad") || (ua.includes("macintosh") && maxTouchPoints > 1);
+
+ // Android tablets drop the "Mobile" token that Android phones send
+ const isTablet = isIPad || (isAndroid && !ua.includes("mobile"));
+ const isMobile = !isTablet && /iphone|ipod|android|mobi/.test(ua);
+
+ return {
+ isDesktop: !isTablet && !isMobile,
+ isAndroid,
+ isMobile,
+ inAppInfo: detectInAppBrowser(ua),
+ };
+}
+
+/**
+ * Identifies the in-app browser / WebView the page is open in, from the (lowercased)
+ * user agent.
+ *
+ * @param ua - The user agent, lowercased.
+ * @returns `isInApp` plus the app's display name, or `{ isInApp: false, name: null }`.
+ */
+function detectInAppBrowser(ua: string): InAppInfo {
+ function has(token: string): boolean {
+ return ua.includes(token);
+ }
+
+ function ios(): boolean {
+ return /iphone|ipad|ipod/.test(ua);
+ }
+
+ for (const detector of IN_APP_BROWSER_DETECTORS) {
+ if (detector.test({ has, ios })) {
+ return { isInApp: true, name: detector.name };
+ }
+ }
+
+ return { isInApp: false, name: null };
+}
+
+interface InAppBrowserDetector {
+ name: string;
+ test: (helpers: {
+ /** Whether the lowercased user agent contains `token`. */
+ has: (token: string) => boolean;
+ /** Whether the user agent is an iPhone, iPad or iPod. */
+ ios: () => boolean;
+ }) => boolean;
+}
+
+/** Checked in order; the first match wins. */
+const IN_APP_BROWSER_DETECTORS: InAppBrowserDetector[] = [
+ {
+ name: "Facebook",
+ test: ({ has }) => {
+ return has("fbav") || has("fban") || has("fb_iab");
+ },
+ },
+ {
+ name: "Instagram",
+ test: ({ has }) => {
+ return has("instagram");
+ },
+ },
+ {
+ name: "Facebook Messenger",
+ test: ({ has }) => {
+ // iOS Messenger: [FBAN/MessengerForiOS;
+ return (
+ has("fban/messengerforio") ||
+ has("messengerforio") ||
+ // Android Messenger: [FB_IAB/MESSENGER;
+ has("fb_iab/messenger") ||
+ // Fallback patterns
+ (has("messenger") && (has("fban") || has("fb_iab")))
+ );
+ },
+ },
+ {
+ name: "WhatsApp",
+ test: ({ has }) => {
+ return has("whatsapp");
+ },
+ },
+ {
+ name: "Telegram",
+ test: ({ has, ios }) => {
+ return (
+ has("telegram") ||
+ has("tgwebview") ||
+ has("telegrambot-like") ||
+ has("tgbot") ||
+ has("telegram-") ||
+ // Bot user agents
+ has("telegrambot") ||
+ // Version-specific patterns
+ has("telegram/") ||
+ // iOS specific patterns
+ (ios() && (has("telegram") || has("tg/"))) ||
+ // Android specific patterns
+ (has("android") && has("tg"))
+ );
+ },
+ },
+ {
+ name: "Twitter/X",
+ test: ({ has }) => {
+ return has("twitter") || has("x-client");
+ },
+ },
+ {
+ name: "LinkedIn",
+ test: ({ has }) => {
+ return has("linkedinapp");
+ },
+ },
+ {
+ name: "Pinterest",
+ test: ({ has }) => {
+ return has("pinterest");
+ },
+ },
+ {
+ name: "Reddit",
+ test: ({ has }) => {
+ return has("reddit");
+ },
+ },
+ {
+ name: "Snapchat",
+ test: ({ has }) => {
+ return has("snapchat");
+ },
+ },
+ {
+ name: "TikTok",
+ test: ({ has }) => {
+ return has("tiktok") || has("com.zhiliaoapp");
+ },
+ },
+ {
+ name: "WeChat",
+ test: ({ has }) => {
+ return has("micromessenger");
+ },
+ },
+ {
+ name: "LINE",
+ test: ({ has }) => {
+ return has("line/");
+ },
+ },
+ {
+ name: "QQ",
+ test: ({ has }) => {
+ return has("qq/");
+ },
+ },
+ {
+ name: "Gmail",
+ test: ({ has }) => {
+ return has("gmail");
+ },
+ },
+ {
+ name: "Google App",
+ test: ({ has }) => {
+ return has("gsa/") || has("googleapp");
+ },
+ },
+ {
+ name: "Discord",
+ test: ({ has }) => {
+ return has("discord");
+ },
+ },
+ {
+ name: "YouTube",
+ test: ({ has }) => {
+ return has("youtube");
+ },
+ },
+ {
+ name: "Android WebView",
+ test: ({ has }) => {
+ return has("wv") && has("android");
+ },
+ },
+ {
+ name: "iOS WebView",
+ test: ({ has, ios }) => {
+ return (
+ ios() &&
+ has("applewebkit") &&
+ !has("safari") &&
+ !has("crios") &&
+ !has("fxios") &&
+ !has("edgios")
+ );
+ },
+ },
+ {
+ name: "Generic WebView",
+ test: ({ has }) => {
+ return (
+ (has("android") && has("webview")) ||
+ (has("mobile safari") && !has("safari"))
+ );
+ },
+ },
+];
diff --git a/src/lib/seo/__tests__/home-json-ld.test.ts b/src/lib/seo/__tests__/home-json-ld.test.ts
index f77f534..602583c 100644
--- a/src/lib/seo/__tests__/home-json-ld.test.ts
+++ b/src/lib/seo/__tests__/home-json-ld.test.ts
@@ -47,7 +47,7 @@ describe("buildHomeJsonLdGraph", () => {
potentialAction: {
"@type": "UseAction",
name: "Start Invoicing",
- target: "https://easyinvoicepdf.com/?template=default",
+ target: "https://easyinvoicepdf.com/",
},
});
@@ -59,7 +59,7 @@ describe("buildHomeJsonLdGraph", () => {
expect.arrayContaining([
expect.objectContaining({
name: "Start Invoicing",
- item: "https://easyinvoicepdf.com/?template=default",
+ item: "https://easyinvoicepdf.com/",
}),
expect.objectContaining({
name: "About",
@@ -75,4 +75,31 @@ describe("buildHomeJsonLdGraph", () => {
hasPart: { "@id": JSON_LD_IDS.siteNavigation },
});
});
+
+ it("describes the route it is rendered on in its WebPage node", () => {
+ const stripeTemplatePage = {
+ url: "https://easyinvoicepdf.com/stripe-template",
+ name: "Stripe Invoice Template - Create Free PDF Invoice",
+ description: "Free Stripe invoice template.",
+ };
+
+ const graph = buildHomeJsonLdGraph(stripeTemplatePage) as unknown as {
+ "@graph": Array<Record<string, unknown>>;
+ };
+
+ const webPages = graph["@graph"].filter((node) => {
+ return node["@type"] === "WebPage";
+ });
+
+ expect(webPages).toEqual([
+ expect.objectContaining({
+ "@id": "https://easyinvoicepdf.com/stripe-template#webpage",
+ url: stripeTemplatePage.url,
+ name: stripeTemplatePage.name,
+ description: stripeTemplatePage.description,
+ isPartOf: { "@id": JSON_LD_IDS.website },
+ mainEntity: { "@id": JSON_LD_IDS.app },
+ }),
+ ]);
+ });
});
diff --git a/src/lib/seo/__tests__/render-json-ld.test.ts b/src/lib/seo/__tests__/render-json-ld.test.ts
new file mode 100644
index 0000000..b65d91c
--- /dev/null
+++ b/src/lib/seo/__tests__/render-json-ld.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { ESCAPED_LESS_THAN, serializeJsonLd } from "../render-json-ld";
+
+describe("serializeJsonLd", () => {
+ const graph = {
+ "@context": "https://schema.org",
+ "@type": "Article",
+ headline: "Fixed </script><script>alert(1)</script> in titles",
+ } as const;
+
+ it("writes `<` as a backslash escape, not the character", () => {
+ // guards the constant itself: the formatter once rewrote it into a plain `<`
+ expect(ESCAPED_LESS_THAN).toHaveLength(6);
+ expect(ESCAPED_LESS_THAN.codePointAt(0)).toBe(0x5c);
+ });
+
+ it("never emits a raw `<`, so the copy cannot close the script tag", () => {
+ const serialized = serializeJsonLd(graph);
+
+ expect(serialized).not.toContain("<");
+ expect(serialized).toContain(`${ESCAPED_LESS_THAN}/script>`);
+ });
+
+ it("parses back to the same data", () => {
+ expect(JSON.parse(serializeJsonLd(graph))).toEqual(graph);
+ });
+});
diff --git a/src/lib/seo/__tests__/site-entities.test.ts b/src/lib/seo/__tests__/site-entities.test.ts
index 7be0c48..43efc3f 100644
--- a/src/lib/seo/__tests__/site-entities.test.ts
+++ b/src/lib/seo/__tests__/site-entities.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest";
+import {
+ SUPPORTED_CURRENCIES,
+ SUPPORTED_INVOICE_PDF_LANGUAGES,
+} from "@/app/schema";
+
import { buildBreadcrumbList } from "../breadcrumb";
import { JSON_LD_IDS } from "../json-ld-ids";
import {
@@ -36,6 +41,28 @@ describe("site-entities", () => {
});
});
+ it("names the site by its brand alone, with other spellings as alternates", () => {
+ // Google reads the site name from WebSite.name and falls back to a guess when it
+ // holds a title-style tagline
+ const webSite = buildFullWebSite();
+ expect(webSite.name).toBe("EasyInvoicePDF");
+ expect(buildSlimWebSite().name).toBe(webSite.name);
+ expect(webSite.alternateName).not.toContain(webSite.name);
+ });
+
+ it("gives the organization a logo of at least 112×112", () => {
+ const { logo } = buildOrganization();
+ expect(logo.url).toMatch(/^https:\/\//);
+ expect(Number(logo.width)).toBeGreaterThanOrEqual(112);
+ expect(Number(logo.height)).toBeGreaterThanOrEqual(112);
+ });
+
+ it("states the real language and currency counts in the feature list", () => {
+ expect(buildWebApplication().featureList).toContain(
+ `Invoices in ${SUPPORTED_INVOICE_PDF_LANGUAGES.length} languages and ${SUPPORTED_CURRENCIES.length} currencies`,
+ );
+ });
+
it("should use real name without role suffix for buildPerson", () => {
const person = buildPerson();
expect(person.name).toBe("Vlad Sazonau");
@@ -53,7 +80,7 @@ describe("site-entities", () => {
expect(app.creator).toMatchObject({ "@id": JSON_LD_IDS.organization });
expect(app.potentialAction).toMatchObject({
name: "Start Invoicing",
- target: "https://easyinvoicepdf.com/?template=default",
+ target: "https://easyinvoicepdf.com/",
});
});
@@ -63,7 +90,7 @@ describe("site-entities", () => {
expect.arrayContaining([
expect.objectContaining({
name: "Start Invoicing",
- item: "https://easyinvoicepdf.com/?template=default",
+ item: "https://easyinvoicepdf.com/",
}),
expect.objectContaining({
name: "About",
@@ -85,10 +112,13 @@ describe("site-entities", () => {
describe("buildBreadcrumbList", () => {
it("should build ordered crumbs with optional last item URL", () => {
- const breadcrumb = buildBreadcrumbList("https://easyinvoicepdf.com/foo", [
- { name: "Start Invoicing", item: "https://easyinvoicepdf.com/" },
- { name: "Foo" },
- ]);
+ const breadcrumb = buildBreadcrumbList({
+ pageUrl: "https://easyinvoicepdf.com/foo",
+ items: [
+ { name: "Start Invoicing", item: "https://easyinvoicepdf.com/" },
+ { name: "Foo" },
+ ],
+ });
expect(breadcrumb).toMatchObject({
"@type": "BreadcrumbList",
diff --git a/src/lib/seo/breadcrumb.ts b/src/lib/seo/breadcrumb.ts
index edf7d8a..1fed273 100644
--- a/src/lib/seo/breadcrumb.ts
+++ b/src/lib/seo/breadcrumb.ts
@@ -8,10 +8,17 @@ interface BreadcrumbItem {
item?: string;
}
-export function buildBreadcrumbList(
- pageUrl: string,
- items: BreadcrumbItem[],
-): BreadcrumbList {
+interface BuildBreadcrumbListParams {
+ /** Absolute URL of the page the trail belongs to; its `#breadcrumb` is the node's `@id`. */
+ pageUrl: string;
+ /** The crumbs, from the site root down to the current page. */
+ items: BreadcrumbItem[];
+}
+
+export function buildBreadcrumbList({
+ pageUrl,
+ items,
+}: BuildBreadcrumbListParams): BreadcrumbList {
return {
"@type": "BreadcrumbList",
"@id": pageBreadcrumbId(pageUrl),
diff --git a/src/lib/seo/indexing-utils.ts b/src/lib/seo/indexing-utils.ts
index 4e508b6..6d067e1 100644
--- a/src/lib/seo/indexing-utils.ts
+++ b/src/lib/seo/indexing-utils.ts
@@ -1,19 +1,14 @@
import { PROD_WEBSITE_URL } from "@/config";
/**
- * Determine indexing-related flags from request search parameters and environment.
+ * Whether this deployment may be indexed at all: the canonical production deployment
+ * (or the local dev server, see below). Preview deployments never are.
*
- * @param searchParams - Query params from request URL.
- * @returns Object with:
- * hasShareableData: Whether query contains 'data' parameter (shareable invoice).
- * isIndexableEnvironment: True if this deployment is allowed to be indexed at all.
- * shouldIndex: True if page should be indexed (indexable environment, no share data).
+ * Depends only on the environment, so it is known at build time and prerendered pages
+ * can use it. Shared invoice links (`?data=`) are kept out of the index separately, by
+ * the `X-Robots-Tag` header in `next.config.mjs`.
*/
-export function computeIndexingFlags(searchParams: {
- [key: string]: string | string[] | undefined;
-}) {
- const hasShareableData = searchParams?.data !== undefined;
-
+export function getIsIndexableEnvironment() {
const isProd =
process.env.VERCEL_ENV === "production" &&
`https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}` === PROD_WEBSITE_URL;
@@ -27,20 +22,5 @@ export function computeIndexingFlags(searchParams: {
*/
const isLocalDevServer = process.env.NODE_ENV === "development";
- const isIndexableEnvironment = isProd || isLocalDevServer;
-
- const shouldIndex = isIndexableEnvironment && !hasShareableData;
-
- return { hasShareableData, isIndexableEnvironment, shouldIndex };
+ return isProd || isLocalDevServer;
}
-
-/**
- * The `content` values Next.js renders for `Metadata.robots` on the invoice app page.
- *
- * Kept here so the client-side sync in `RobotsMetaSync` writes exactly what
- * `resolveAppPageRobots` would have rendered for the same state.
- */
-export const ROBOTS_META_CONTENT = {
- indexable: "index, follow",
- nonIndexable: "noindex, nofollow",
-} as const;
diff --git a/src/lib/seo/render-json-ld.tsx b/src/lib/seo/render-json-ld.tsx
index 95f238c..4f39f4f 100644
--- a/src/lib/seo/render-json-ld.tsx
+++ b/src/lib/seo/render-json-ld.tsx
@@ -1,23 +1,41 @@
import type { Graph, WithContext, Thing } from "schema-dts";
interface JsonLdScriptProps {
+ /** Unique id for the script tag (for deduping and SSR stability). */
id: string;
+ /** JSON-LD object: a schema.org graph or a context-wrapped thing. */
data: Graph | WithContext<Thing>;
}
/**
* Render JSON-LD as <script type="application/ld+json"> for SEO.
*
- * @param {Object} props
- * @param {string} props.id - Unique id for script tag (for deduping/SSR stability).
- * @param {Graph | WithContext<Thing>} props.data - JSON-LD object (schema.org graph or context-wrapped thing).
+ * The graphs carry copy from MDX front matter and landing definitions, and
+ * `JSON.stringify` leaves `<` alone: a `</script>` anywhere in that text would close the
+ * tag early, dropping the rest of the graph and letting the remainder run as HTML.
+ * {@link serializeJsonLd} writes `<` as its JSON escape instead, which parses back to the
+ * same data. This is the escaping Next.js recommends for JSON-LD.
*/
export function JsonLdScript({ id, data }: JsonLdScriptProps) {
return (
<script
id={id}
type="application/ld+json"
- dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }}
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
/>
);
}
+
+/**
+ * The JSON escape for `<`: a backslash, then `u003c`.
+ *
+ * Built from the backslash's code point because `oxfmt` rewrites unicode escapes in
+ * string and template literals (`String.raw` included, and even in comments) into the
+ * character itself, which silently turned this escape back into a plain `<`.
+ */
+export const ESCAPED_LESS_THAN = `${String.fromCodePoint(0x5c)}u003c`;
+
+/** `JSON.stringify`, with every `<` written as its JSON escape so the output can't end the tag. */
+export function serializeJsonLd(data: Graph | WithContext<Thing>) {
+ return JSON.stringify(data).replaceAll("<", ESCAPED_LESS_THAN);
+}
diff --git a/src/lib/seo/site-entities.ts b/src/lib/seo/site-entities.ts
index 4ef1fc7..2a63385 100644
--- a/src/lib/seo/site-entities.ts
+++ b/src/lib/seo/site-entities.ts
@@ -7,11 +7,17 @@
* - author.name = person name only (no role suffix per Google Article guide).
*/
+import { APP_PAGE_TITLE } from "@/app/(main)/(app)/app-page-heading";
+import {
+ SUPPORTED_CURRENCIES,
+ SUPPORTED_INVOICE_PDF_LANGUAGES,
+} from "@/app/schema";
import {
FOUNDER_AVATAR_URL,
GITHUB_URL,
LINKEDIN_URL,
PERSONAL_WEBSITE_URL,
+ PRODUCT_TWITTER_URL,
PROD_WEBSITE_URL,
STATIC_ASSETS_URL,
TWITTER_URL,
@@ -19,12 +25,23 @@ import {
import { JSON_LD_BASE, JSON_LD_IDS } from "./json-ld-ids";
-export const SITE_NAME =
- "EasyInvoicePDF | Free & Open-Source Invoice Generator – Live Preview, No Sign-Up";
+/**
+ * The site's name, as Google should print it above a result.
+ *
+ * Google reads site names from `WebSite.name` and expects the name itself, not a title:
+ * a tagline after the brand makes it fall back to a guess from the page title. Other
+ * spellings people use go in `alternateName`.
+ */
+const SITE_NAME = "EasyInvoicePDF";
+
+const SITE_ALTERNATE_NAMES = ["EasyInvoicePDF.com", "Easy Invoice PDF"];
const SITE_DESCRIPTION =
"Create and download professional invoices instantly with EasyInvoicePDF. Free and open-source. No signup required.";
+/** The `<title>` of `/`, also the name of its `WebPage` node. */
+export const HOME_PAGE_TITLE = APP_PAGE_TITLE.default;
+
export const HOME_PAGE_DESCRIPTION =
"Create professional PDF invoices online for free. Customize invoice templates, add your logo, download instantly, and send invoices without signup.";
@@ -37,16 +54,20 @@ export const FOUNDER_PAGE_DESCRIPTION =
export const OG_IMAGE_URL = `${STATIC_ASSETS_URL}/easy-invoice-opengraph-image.png?v=1755773879597`;
-const START_INVOICING_URL = `${JSON_LD_BASE}/?template=default`;
+/** Square, 180×180: Google wants an Organization logo of at least 112×112. */
+const ORGANIZATION_LOGO_URL = `${STATIC_ASSETS_URL}/apple-icon.png`;
+
+const START_INVOICING_URL = `${JSON_LD_BASE}/`;
const WEB_APPLICATION_FEATURES = [
"Live preview as you type",
"No sign-up needed",
"No ads",
"Save seller and buyer details for future reuse",
- "Flexible tax: VAT, GST, custom options",
- "Fully customizable invoice templates",
- "Supports 10+ languages, all major currencies",
+ "Flexible tax: VAT, GST, Sales Tax or a custom label",
+ "Two invoice templates: a classic layout and a Stripe-style one",
+ // derived from the schema, so the counts can't go stale when a language is added
+ `Invoices in ${SUPPORTED_INVOICE_PDF_LANGUAGES.length} languages and ${SUPPORTED_CURRENCIES.length} currencies`,
"One-click instant PDF download",
"Browser only, data stays private",
"Share via link, no attachments",
@@ -68,7 +89,7 @@ export function buildFullWebSite() {
"@id": JSON_LD_IDS.website,
url: `${JSON_LD_BASE}/`,
name: SITE_NAME,
- alternateName: ["EasyInvoicePDF", "easyinvoicepdf.com"],
+ alternateName: [...SITE_ALTERNATE_NAMES],
description: SITE_DESCRIPTION,
inLanguage: "en",
publisher: {
@@ -87,9 +108,15 @@ export function buildOrganization() {
return {
"@type": "Organization" as const,
"@id": JSON_LD_IDS.organization,
- name: "EasyInvoicePDF",
+ name: SITE_NAME,
url: `${JSON_LD_BASE}/`,
- sameAs: [GITHUB_URL],
+ logo: {
+ "@type": "ImageObject" as const,
+ url: ORGANIZATION_LOGO_URL,
+ width: "180",
+ height: "180",
+ },
+ sameAs: [GITHUB_URL, PRODUCT_TWITTER_URL],
};
}
diff --git a/src/utils/__tests__/invoice-app-url.test.ts b/src/utils/__tests__/invoice-app-url.test.ts
new file mode 100644
index 0000000..41e33b4
--- /dev/null
+++ b/src/utils/__tests__/invoice-app-url.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ buildInvoiceAppUrl,
+ getRouteTemplate,
+ getTemplateFromUrl,
+ isUrlForTemplate,
+ STRIPE_TEMPLATE_PATHNAME,
+} from "../invoice-app-url";
+
+describe("getTemplateFromUrl", () => {
+ it("reads the Stripe template from its route, whatever the query says", () => {
+ expect(
+ getTemplateFromUrl({
+ pathname: STRIPE_TEMPLATE_PATHNAME,
+ searchParams: new URLSearchParams("template=default"),
+ }),
+ ).toBe("stripe");
+ });
+
+ it("has no preference on a bare root route", () => {
+ expect(
+ getTemplateFromUrl({
+ pathname: "/",
+ searchParams: new URLSearchParams("data=abc"),
+ }),
+ ).toBeNull();
+
+ expect(
+ getTemplateFromUrl({
+ pathname: "/",
+ searchParams: new URLSearchParams("template=unknown"),
+ }),
+ ).toBeNull();
+ });
+
+ it("honours a legacy ?template= on the root route", () => {
+ expect(
+ getTemplateFromUrl({
+ pathname: "/",
+ searchParams: new URLSearchParams("template=default"),
+ }),
+ ).toBe("default");
+
+ // in case one arrives without going through the redirect
+ expect(
+ getTemplateFromUrl({
+ pathname: "/",
+ searchParams: new URLSearchParams("template=stripe"),
+ }),
+ ).toBe("stripe");
+ });
+});
+
+describe("getRouteTemplate", () => {
+ it("reads the template from the route alone", () => {
+ expect(getRouteTemplate(STRIPE_TEMPLATE_PATHNAME)).toBe("stripe");
+ expect(getRouteTemplate("/")).toBe("default");
+ });
+});
+
+describe("buildInvoiceAppUrl", () => {
+ it("puts each template on its route, without ?template=", () => {
+ expect(buildInvoiceAppUrl({ template: "default" })).toBe("/");
+ expect(buildInvoiceAppUrl({ template: "stripe" })).toBe(
+ STRIPE_TEMPLATE_PATHNAME,
+ );
+ });
+
+ it("drops a legacy ?template= and keeps the other params in order", () => {
+ expect(
+ buildInvoiceAppUrl({
+ template: "default",
+ searchParams: new URLSearchParams("template=default&data=abc&utm=x"),
+ }),
+ ).toBe("/?data=abc&utm=x");
+
+ expect(
+ buildInvoiceAppUrl({
+ template: "stripe",
+ searchParams: new URLSearchParams("template=stripe&data=abc"),
+ }),
+ ).toBe(`${STRIPE_TEMPLATE_PATHNAME}?data=abc`);
+ });
+
+ it("does not mutate the params it is given", () => {
+ const searchParams = new URLSearchParams("template=stripe&data=abc");
+
+ buildInvoiceAppUrl({ template: "stripe", searchParams });
+
+ expect(searchParams.toString()).toBe("template=stripe&data=abc");
+ });
+});
+
+describe("isUrlForTemplate", () => {
+ it("accepts each template's route, whatever the other params", () => {
+ expect(
+ isUrlForTemplate({
+ template: "default",
+ pathname: "/",
+ searchParams: new URLSearchParams("data=abc"),
+ }),
+ ).toBe(true);
+
+ expect(
+ isUrlForTemplate({
+ template: "stripe",
+ pathname: STRIPE_TEMPLATE_PATHNAME,
+ searchParams: new URLSearchParams("data=abc"),
+ }),
+ ).toBe(true);
+ });
+
+ it("rejects the wrong route", () => {
+ expect(
+ isUrlForTemplate({
+ template: "stripe",
+ pathname: "/",
+ searchParams: new URLSearchParams(),
+ }),
+ ).toBe(false);
+
+ expect(
+ isUrlForTemplate({
+ template: "default",
+ pathname: STRIPE_TEMPLATE_PATHNAME,
+ searchParams: new URLSearchParams(),
+ }),
+ ).toBe(false);
+ });
+
+ it("rejects a leftover legacy ?template=", () => {
+ expect(
+ isUrlForTemplate({
+ template: "default",
+ pathname: "/",
+ searchParams: new URLSearchParams("template=default"),
+ }),
+ ).toBe(false);
+
+ expect(
+ isUrlForTemplate({
+ template: "stripe",
+ pathname: STRIPE_TEMPLATE_PATHNAME,
+ searchParams: new URLSearchParams("template=stripe"),
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/utils/browser-support.ts b/src/utils/browser-support.ts
index 63e0f68..2d92a04 100644
--- a/src/utils/browser-support.ts
+++ b/src/utils/browser-support.ts
@@ -2,10 +2,9 @@
* Client-side "is this browser too old?" check, used to nudge visitors on a stale
* browser towards updating (`src/components/browser-support-notice.tsx`).
*
- * Deliberately hand-rolled instead of reusing `ua-parser-js` (already a dependency,
- * but server-only today): all we need is the major version of the six engines that
- * make up practically all of the traffic, and that is a handful of regexes rather
- * than ~7 kB gzip of parser in the client bundle.
+ * Deliberately hand-rolled instead of using `ua-parser-js`: all we need is the major
+ * version of the six engines that make up practically all of the traffic, and that is
+ * a handful of regexes rather than ~7 kB gzip of parser in the client bundle.
*
* Everything here is a pure function of the user agent string so it can be unit
* tested without a DOM — see `__tests__/browser-support.test.ts`.
diff --git a/src/utils/invoice-app-url.ts b/src/utils/invoice-app-url.ts
new file mode 100644
index 0000000..17e258c
--- /dev/null
+++ b/src/utils/invoice-app-url.ts
@@ -0,0 +1,114 @@
+import { SUPPORTED_TEMPLATES, type SupportedTemplates } from "@/app/schema";
+
+/**
+ * The Stripe template has its own route, so it is prerendered with its own title,
+ * canonical URL and OG image. The default template lives at `/`.
+ *
+ * A bare `/` also means "the app, with whatever template I used last": a visitor whose
+ * saved invoice uses Stripe is moved on to `/stripe-template`. Only `/stripe-template`
+ * asks for a template explicitly.
+ *
+ * Legacy links still work: `/?template=stripe` is permanently redirected here
+ * (`next.config.mjs`), and `/?template=default` is honoured once and then dropped from
+ * the address bar.
+ */
+export const STRIPE_TEMPLATE_PATHNAME = "/stripe-template";
+
+interface GetTemplateFromUrlParams {
+ /** The current pathname, e.g. `usePathname()`. */
+ pathname: string;
+ /** The current query string. */
+ searchParams: Pick<URLSearchParams, "get">;
+}
+
+/**
+ * Reads the invoice template the URL asks for.
+ *
+ * The route wins over the query: `/stripe-template` is always the Stripe template. On `/`
+ * only a legacy `?template=` param asks for one; a bare `/` expresses no preference.
+ *
+ * @returns The requested template, or `null` when the URL does not ask for one.
+ */
+export function getTemplateFromUrl({
+ pathname,
+ searchParams,
+}: GetTemplateFromUrlParams): SupportedTemplates | null {
+ if (pathname === STRIPE_TEMPLATE_PATHNAME) {
+ return "stripe";
+ }
+
+ const templateParam = searchParams.get("template");
+
+ return (
+ SUPPORTED_TEMPLATES.find((template) => {
+ return template === templateParam;
+ }) ?? null
+ );
+}
+
+/**
+ * The template of the route itself, ignoring any query string: the route a template
+ * switch moves away from or to.
+ *
+ * @param pathname - The current pathname.
+ * @returns `stripe` on `/stripe-template`, `default` anywhere else.
+ */
+export function getRouteTemplate(pathname: string): SupportedTemplates {
+ return pathname === STRIPE_TEMPLATE_PATHNAME ? "stripe" : "default";
+}
+
+interface IsUrlForTemplateParams extends GetTemplateFromUrlParams {
+ /** The template the URL should open. */
+ template: SupportedTemplates;
+ searchParams: Pick<URLSearchParams, "get" | "has">;
+}
+
+/**
+ * Whether the URL is already in the canonical shape `buildInvoiceAppUrl` produces for
+ * `template` -- the template's route, without a (legacy) `?template=` param. Other
+ * params are not looked at.
+ *
+ * @returns `true` when nothing about the template needs rewriting.
+ */
+export function isUrlForTemplate({
+ template,
+ pathname,
+ searchParams,
+}: IsUrlForTemplateParams): boolean {
+ return (
+ pathname === TEMPLATE_PATHNAMES[template] && !searchParams.has("template")
+ );
+}
+
+interface BuildInvoiceAppUrlParams {
+ /** The template the URL should open. */
+ template: SupportedTemplates;
+ /** Query params to keep (`?data=`, utm tags, ...). Not mutated. */
+ searchParams?: URLSearchParams;
+}
+
+/**
+ * Builds the root-relative URL of the invoice app for a template, e.g. `/?data=...` or
+ * `/stripe-template?data=...`. A legacy `?template=` param is dropped: the route says
+ * which template it is.
+ *
+ * @returns The pathname plus query string.
+ */
+export function buildInvoiceAppUrl({
+ template,
+ searchParams,
+}: BuildInvoiceAppUrlParams): string {
+ const params = new URLSearchParams(searchParams);
+ params.delete("template");
+
+ const pathname = TEMPLATE_PATHNAMES[template];
+ const query = params.toString();
+
+ return query ? `${pathname}?${query}` : pathname;
+}
+
+/** The route each template lives at. */
+const TEMPLATE_PATHNAMES = {
+ default: "/",
+ stripe: STRIPE_TEMPLATE_PATHNAME,
+} as const satisfies Record<SupportedTemplates, string>;