You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I needed a solution that would let me customize dynamically Metadata on my Vite React SPA with Tanstack Router. So I developed this:
Actual Code
// MetadataManager.tsximport{useMatch,useMatches,useRouterState}from'@tanstack/react-router';import{useEffect,createContext,useContext,useState,ReactNode,useMemo,useCallback,useRef}from'react';importcreateDOMPurifyfrom'dompurify';constDOMPurify=createDOMPurify(window);exportinterfaceCustomMetadataProps{title?: string;description?: string;keywords?: string[];author?: string;robots?: string;viewport?: string;canonicalUrl?: string;themeColor?: string;favicon?: string;ogTitle?: string;ogDescription?: string;ogImage?: string;ogType?: string;ogUrl?: string;twitterCard?: string;twitterTitle?: string;twitterDescription?: string;twitterImage?: string;twitterCreator?: string;twitterSite?: string;}typeMetadataContextType={setMetadata: (metadata: Partial<CustomMetadataProps>)=>void;};constMetadataContext=createContext<MetadataContextType|null>(null);exportfunctionuseMetadata(){constcontext=useContext(MetadataContext);if(!context){thrownewError('useMetadata must be used within a MetadataProvider');}returncontext;}constDEFAULT_METADATA: CustomMetadataProps={title: 'My App',description: 'A modern web application',keywords: ['web','app','react'],author: 'Your Name',robots: 'index, follow',viewport: 'width=device-width, initial-scale=1',canonicalUrl: '',themeColor: '#000000',favicon: '/favicon.ico',ogTitle: 'My App',ogDescription: 'A modern web application',ogImage: '/og-image.png',ogType: 'website',ogUrl: '',twitterCard: 'summary_large_image',twitterTitle: 'My App',twitterDescription: 'A modern web application',twitterImage: '/twitter-image.png',twitterCreator: '@username',twitterSite: '@username'};exportfunctionMetadataProvider({ children }: {children: ReactNode}){const[dynamicMetadata,setDynamicMetadata]=useState<Partial<CustomMetadataProps>>({});constsetMetadata=useCallback((metadata: Partial<CustomMetadataProps>)=>{setDynamicMetadata(prev=>{consthasChanges=Object.entries(metadata).some(([key,value])=>prev[keyaskeyofCustomMetadataProps]!==value);returnhasChanges ? { ...prev, ...metadata} : prev;});},[]);constvalue=useMemo(()=>({ setMetadata }),[setMetadata]);return(<MetadataContext.Providervalue={value}><MetadataManagerdynamicMetadata={dynamicMetadata}/>{children}</MetadataContext.Provider>);}constsanitizeContent=(content: string|undefined): string=>{if(!content)return'';returnDOMPurify.sanitize(String(content),{ALLOWED_TAGS: [],ALLOWED_ATTR: []});};constisValidUrl=(url: string|undefined): boolean=>{if(!url)returnfalse;try{if(url.startsWith('/'))returntrue;constparsed=newURL(url);returnparsed.protocol==='https:'&&!url.startsWith('//')&&!url.match(/^(data|javascript|vbscript|file):/i);}catch{returnfalse;}};constsanitizeUrl=(url: string|undefined): string=>{if(!url)return'';if(!isValidUrl(url))return'';returnDOMPurify.sanitize(url,{ALLOWED_TAGS: [],ALLOWED_ATTR: []});};typeMetadataManagerProps={dynamicMetadata?: CustomMetadataProps;};exportfunctionMetadataManager({ dynamicMetadata ={}}: MetadataManagerProps){constmatches=useMatches();constmatch=matches[matches.length-1];const{ location }=useRouterState();constpreviousPathRef=useRef(location.pathname);constmetadataRef=useRef<(HTMLMetaElement|HTMLLinkElement)[]>([]);constfaviconRef=useRef<HTMLLinkElement[]>([]);constprevMetadataRef=useRef<CustomMetadataProps|null>(null);constmetadata=useMemo(()=>{constmerged={ ...DEFAULT_METADATA};Object.entries(dynamicMetadata).forEach(([key,value])=>{if(value!==undefined){merged[keyaskeyofCustomMetadataProps]=value;}});Object.entries(match.staticData).forEach(([key,value])=>{if(value!==undefined){merged[keyaskeyofCustomMetadataProps]=value;}});if(!merged.twitterImage&&merged.ogImage){merged.twitterImage=merged.ogImage;}returnmerged;},[dynamicMetadata,match.staticData]);constshouldUpdate=useMemo(()=>{if(!prevMetadataRef.current){prevMetadataRef.current=metadata;returntrue;}consthasChanges=Object.entries(metadata).some(([key,value])=>prevMetadataRef.current?.[keyaskeyofCustomMetadataProps]!==value);if(hasChanges){prevMetadataRef.current=metadata;}returnhasChanges;},[metadata]);constcleanup=useCallback(()=>{metadataRef.current.forEach(tag=>tag.remove());metadataRef.current=[];faviconRef.current.forEach(tag=>tag.remove());faviconRef.current=[];},[]);constsetMetaTag=useCallback((name: string,content: string|undefined,property?: string)=>{if(!content)returnnull;constcontentToUse=property?.includes('image') ? sanitizeUrl(content) : sanitizeContent(content);if(!contentToUse)returnnull;constnameToUse=sanitizeContent(name);constpropertyToUse=property ? sanitizeContent(property) : '';constselector=property ? `meta[property="${propertyToUse}"]` : `meta[name="${nameToUse}"]`;letmeta=document.querySelector(selector)asHTMLMetaElement;if(!meta){meta=document.createElement('meta');if(property){meta.setAttribute('property',propertyToUse);}else{meta.setAttribute('name',nameToUse);}document.head.appendChild(meta);metadataRef.current.push(meta);}constcurrentContent=meta.getAttribute('content');if(currentContent!==contentToUse){meta.setAttribute('content',contentToUse);}returnmeta;},[]);constupdateFavicon=useCallback((faviconUrl: string)=>{try{faviconRef.current.forEach(tag=>tag.remove());faviconRef.current=[];document.querySelectorAll('link[rel*="icon"]').forEach(el=>{if(!faviconRef.current.includes(elasHTMLLinkElement)){el.remove();}});if(isValidUrl(faviconUrl)){constsanitizedUrl=sanitizeUrl(faviconUrl);if(!sanitizedUrl)return;constlink=document.createElement('link');link.rel='icon';link.href=sanitizedUrl;document.head.appendChild(link);faviconRef.current.push(link);constappleLink=document.createElement('link');appleLink.rel='apple-touch-icon';appleLink.href=sanitizedUrl;document.head.appendChild(appleLink);faviconRef.current.push(appleLink);}}catch(error){console.error('Error updating favicon:',error);}},[]);useEffect(()=>{constcurrentPath=location.pathname;if(previousPathRef.current!==currentPath){cleanup();previousPathRef.current=currentPath;}if(!shouldUpdate)return;consttitle=sanitizeContent(metadata.title);if(document.title!==title){document.title=title;}setMetaTag('description',metadata.description);setMetaTag('keywords',metadata.keywords?.map(sanitizeContent).join(', '));setMetaTag('author',metadata.author);setMetaTag('robots',metadata.robots);setMetaTag('viewport',metadata.viewport);setMetaTag('theme-color',metadata.themeColor);if(isValidUrl(metadata.canonicalUrl)){letlink=document.querySelector('link[rel="canonical"]')asHTMLLinkElement;if(!link){link=document.createElement('link');document.head.appendChild(link);metadataRef.current.push(link);}link.rel='canonical';link.href=sanitizeUrl(metadata.canonicalUrl)||'';}setMetaTag('og:title',metadata.ogTitle,'og:title');setMetaTag('og:description',metadata.ogDescription,'og:description');if(isValidUrl(metadata.ogImage)){setMetaTag('og:image',metadata.ogImage,'og:image');setMetaTag('og:image:secure_url',metadata.ogImage,'og:image:secure_url');}setMetaTag('og:type',metadata.ogType,'og:type');if(isValidUrl(metadata.ogUrl)){setMetaTag('og:url',metadata.ogUrl,'og:url');}setMetaTag('twitter:card',metadata.twitterCard);setMetaTag('twitter:title',metadata.twitterTitle);setMetaTag('twitter:description',metadata.twitterDescription);if(isValidUrl(metadata.twitterImage)){setMetaTag('twitter:image',metadata.twitterImage);}setMetaTag('twitter:creator',metadata.twitterCreator);setMetaTag('twitter:site',metadata.twitterSite);if(metadata.favicon){updateFavicon(metadata.favicon);}returncleanup;},[shouldUpdate,location.pathname,cleanup,setMetaTag,updateFavicon,metadata]);useEffect(()=>{letmanifestLink=document.querySelector('link[rel="manifest"]')asHTMLLinkElement|null;if(!manifestLink){manifestLink=document.createElement('link');manifestLink.rel='manifest';manifestLink.href='/manifest.json';document.head.appendChild(manifestLink);metadataRef.current.push(manifestLink);}},[]);returnnull;}
Basic set up
// somewhere in main.tsx or in your type declarationsdeclare module '@tanstack/react-router'{interfaceRegister{router: typeofrouter}interfaceStaticDataRouteOptionextendsCustomMetadataProps{}}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I needed a solution that would let me customize dynamically Metadata on my Vite React SPA with Tanstack Router. So I developed this:
Actual Code
Basic set up
How to use?
There are two ways of using this, by specifying
staticDataon the tanstack route or by using thesetMetadatafrom the Context.or
Hope that this would be helpful to anyone, and would appreciate any suggestion on improvements to this component, would love to ear feedback!
Beta Was this translation helpful? Give feedback.
All reactions