fix(seo): resolve technical SEO issues (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15)
Deploy Canina / deploy (push) Successful in 2m11s
Deploy Canina / deploy (push) Successful in 2m11s
- SEO-P0-01: prioritize options.canonicalPath in getPageMetadata over shop_canonical text - SEO-P0-02: invoke notFound() in /shop/[slug] and /wiki/[slug] when entity is missing - SEO-P1-06: package root JSON-LD Organization and WebSite into @graph structure - SEO-P2-15: add hreflang fa-IR and x-default alternates in root layout metadata - Add regression test suite lib/__tests__/seo-technical.test.ts
This commit is contained in:
1 parent
87bf867513
commit
5cf2863987
5 files changed
+170
-13
No files matched your search
@@ -71,6 +71,10 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
},
|
||||
alternates: {
|
||||
canonical: '/',
|
||||
languages: {
|
||||
'fa-IR': `${siteUrl}/`,
|
||||
'x-default': `${siteUrl}/`,
|
||||
},
|
||||
},
|
||||
formatDetection: {
|
||||
email: false,
|
||||
@@ -148,7 +152,12 @@ export default async function RootLayout({
|
||||
},
|
||||
};
|
||||
|
||||
const safeJsonLd = JSON.stringify([orgSchema, webSiteSchema]).replace(/</g, '\\u003c');
|
||||
const rootSchemaGraph = {
|
||||
'@context': 'https://schema.org',
|
||||
'@graph': [orgSchema, webSiteSchema],
|
||||
};
|
||||
|
||||
const safeJsonLd = JSON.stringify(rootSchemaGraph).replace(/</g, '\\u003c');
|
||||
|
||||
const gaId = config.googleAnalyticsId?.trim();
|
||||
const isGaEnabled = Boolean(gaId && config.enableGoogleAnalytics !== false);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import ProductPage from "../../../components/ProductPage";
|
||||
import { productService } from "../../../lib/services/productService";
|
||||
import type { Metadata } from 'next';
|
||||
@@ -133,7 +134,7 @@ export default async function ShopProductPage({ params }: { params: Promise<{ sl
|
||||
const product = await productService.getProductBySlug(resolvedParams.slug);
|
||||
|
||||
if (!product) {
|
||||
return <ProductPage productSlug={resolvedParams.slug} initialProduct={product} />;
|
||||
notFound();
|
||||
}
|
||||
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://canina.ir';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { ChevronRight, Sparkles, Package, ArrowLeft, ShieldCheck } from 'lucide-react';
|
||||
import type { Metadata } from 'next';
|
||||
@@ -81,15 +82,7 @@ export default async function WikiTermPage({ params }: { params: Promise<{ slug:
|
||||
const term = await getWikiTerm(slug);
|
||||
|
||||
if (!term) {
|
||||
return (
|
||||
<div className="min-h-[50vh] flex flex-col items-center justify-center font-vazir text-center px-4" dir="rtl">
|
||||
<h1 className="text-3xl font-black text-medical-gray-900 mb-4">ترکیب علمی یافت نشد</h1>
|
||||
<Link href="/wiki" className="text-canina-blue font-bold flex items-center gap-2">
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
بازگشت به دانشنامه
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
notFound();
|
||||
}
|
||||
|
||||
const relatedProducts = await getRelatedProducts(term.term);
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { getPageMetadata } from '../seo';
|
||||
|
||||
const mockFetch = vi.fn();
|
||||
global.fetch = mockFetch;
|
||||
|
||||
// Mock next/navigation
|
||||
const mockNotFound = vi.fn();
|
||||
vi.mock('next/navigation', () => ({
|
||||
notFound: () => {
|
||||
mockNotFound();
|
||||
throw new Error('NEXT_NOT_FOUND');
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock next/font/local and next/font/google
|
||||
vi.mock('next/font/local', () => ({
|
||||
default: () => ({ variable: '--font-vazir' }),
|
||||
}));
|
||||
vi.mock('next/font/google', () => ({
|
||||
Lalezar: () => ({ variable: '--font-lalezar' }),
|
||||
}));
|
||||
|
||||
// Mock productService
|
||||
const mockGetProductBySlug = vi.fn();
|
||||
vi.mock('../../lib/services/productService', () => ({
|
||||
productService: {
|
||||
getProductBySlug: (slug: string) => mockGetProductBySlug(slug),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('SEO Technical Fixes (SEO-P0-01, SEO-P0-02, SEO-P1-06, SEO-P2-15)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
delete process.env.NEXT_PUBLIC_APP_ENV;
|
||||
delete process.env.NEXT_PUBLIC_SITE_URL;
|
||||
});
|
||||
|
||||
describe('SEO-P0-01: Canonical tag for category pages in lib/seo.ts', () => {
|
||||
it('should NOT let global shop_canonical override options.canonicalPath', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
shop_canonical: 'https://canina.ir/shop',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
}),
|
||||
});
|
||||
|
||||
const metadata = await getPageMetadata('shop', {
|
||||
canonicalPath: '/shop?category=joints',
|
||||
});
|
||||
|
||||
expect(metadata.alternates?.canonical).toBe('https://canina.ir/shop?category=joints');
|
||||
});
|
||||
|
||||
it('should fall back to shop_canonical if options.canonicalPath is not provided', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
shop_canonical: 'https://canina.ir/shop-override',
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
}),
|
||||
});
|
||||
|
||||
const metadata = await getPageMetadata('shop');
|
||||
expect(metadata.alternates?.canonical).toBe('https://canina.ir/shop-override');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SEO-P0-02: Soft 404 handling with notFound()', () => {
|
||||
it('should call notFound() in ShopProductPage when product is not found', async () => {
|
||||
const { default: ShopProductPage } = await import('../../app/shop/[slug]/page');
|
||||
mockGetProductBySlug.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(ShopProductPage({
|
||||
params: Promise.resolve({ slug: 'non-existent-product' })
|
||||
})).rejects.toThrow('NEXT_NOT_FOUND');
|
||||
|
||||
expect(mockNotFound).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should call notFound() in WikiTermPage when term is not found', async () => {
|
||||
const { default: WikiTermPage } = await import('../../app/wiki/[slug]/page');
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 404,
|
||||
});
|
||||
|
||||
await expect(WikiTermPage({
|
||||
params: Promise.resolve({ slug: 'non-existent-term' })
|
||||
})).rejects.toThrow('NEXT_NOT_FOUND');
|
||||
|
||||
expect(mockNotFound).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SEO-P2-15: hreflang alternates in RootLayout metadata', () => {
|
||||
it('should configure alternates with languages fa-IR and x-default in app/layout.tsx', async () => {
|
||||
const { generateMetadata } = await import('../../app/layout');
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
canonicalBaseUrl: 'https://canina.ir',
|
||||
}),
|
||||
});
|
||||
|
||||
const metadata = await generateMetadata();
|
||||
expect(metadata.alternates?.languages).toBeDefined();
|
||||
expect(metadata.alternates?.languages?.['fa-IR']).toBe('https://canina.ir/');
|
||||
expect(metadata.alternates?.languages?.['x-default']).toBe('https://canina.ir/');
|
||||
});
|
||||
});
|
||||
|
||||
describe('SEO-P1-06: Schema @graph formatting in RootLayout', () => {
|
||||
it('should package Organization and WebSite inside @graph structure', async () => {
|
||||
const { default: RootLayout } = await import('../../app/layout');
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
texts: {},
|
||||
}),
|
||||
});
|
||||
|
||||
const element = await RootLayout({ children: null });
|
||||
const findScript = (node: any): any => {
|
||||
if (!node) return null;
|
||||
if (node.type === 'script' && node.props?.type === 'application/ld+json') {
|
||||
return node;
|
||||
}
|
||||
if (Array.isArray(node)) {
|
||||
for (const item of node) {
|
||||
const found = findScript(item);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
if (node.props?.children) {
|
||||
return findScript(node.props.children);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const script = findScript(element);
|
||||
expect(script).toBeDefined();
|
||||
const jsonContent = JSON.parse(script.props.dangerouslySetInnerHTML.__html);
|
||||
|
||||
expect(jsonContent['@context']).toBe('https://schema.org');
|
||||
expect(Array.isArray(jsonContent['@graph'])).toBe(true);
|
||||
const types = jsonContent['@graph'].map((item: any) => item['@type']);
|
||||
expect(types).toContain('Organization');
|
||||
expect(types).toContain('WebSite');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -277,9 +277,10 @@ export async function getPageMetadata(
|
||||
? rawKeywords.split(',').map((k) => k.trim()).filter(Boolean)
|
||||
: options.fallbackKeywords || config.keywords;
|
||||
|
||||
const explicitCanonical = texts[`${pageKey}_canonical`];
|
||||
const relativePath = options.canonicalPath ?? (isHome ? '/' : `/${pageKey.replace(/_/g, '-')}`);
|
||||
const canonicalUrl = explicitCanonical || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`;
|
||||
const canonicalUrl = options.canonicalPath
|
||||
? `${canonicalBaseUrl.replace(/\/$/, '')}${options.canonicalPath.startsWith('/') ? options.canonicalPath : `/${options.canonicalPath}`}`
|
||||
: (texts[`${pageKey}_canonical`] || `${canonicalBaseUrl.replace(/\/$/, '')}${relativePath}`);
|
||||
|
||||
const image = options.ogImage || ogImageUrl;
|
||||
|
||||
|
||||
Reference in new issue
Block a user