Add script tag to <head> from within a sub route
Unanswered
Indian Spitz posted this in #help-forum
Indian SpitzOP
Created a post earlier which I thought were working and it was marked solved so have to create another one now.
I'm trying to add a <script> tag with dynamic content which I need for SEO purposes to be able to add ld+json schema.org content.
I've tried adding this to both
Thing is, it works on first initial load, but when I navigate using the <Link> component to the root page and then back to another article the content isn't updated.
Also tried different strategies on the <Script> tag without success.
Is this the right approach of doing this or are there better ways? Or is it a bug?
Many thanks in advance!
I'm trying to add a <script> tag with dynamic content which I need for SEO purposes to be able to add ld+json schema.org content.
I've tried adding this to both
/article/[id]/page.tsx and /article/[id]/layout.tsx: <Script
id="schema.org"
type="application/ld+json"
strategy="afterInteractive"
key={content.id}
>
{JSON.stringify(generateRecipeJSONLD(content))}
</Script>Thing is, it works on first initial load, but when I navigate using the <Link> component to the root page and then back to another article the content isn't updated.
Also tried different strategies on the <Script> tag without success.
Is this the right approach of doing this or are there better ways? Or is it a bug?
Many thanks in advance!
6 Replies
European sprat
you're likely encountering the client side Router Cache
which is 30 seconds for dynamic pages and 5 minutes for static pages
Indian SpitzOP
Ah that makes sense! I read about it in the discussion thread on github and I guess I have to wait for them to add the possability to lower that to 0 seconds
European sprat
i haven't tested this but i saw it mentioned in a discussion about caching:
use this in onClick for an "a" tag (rather than <Link>):
use this in onClick for an "a" tag (rather than <Link>):
const clearCacheAndPush = (e) => {
e.preventDefault();
React.startTransition(() => {
router.refresh();
router.push(href);
})
}which will reset the router cache and push to the page you want
Indian SpitzOP
Didn't help, I wonder if the Router Cache is the issue. I tried creating a custom Link component like so:
And replaced all the uses of
Appreciate the help though!
'use client';
import { useRouter } from 'next/navigation';
import { ReactNode, startTransition } from 'react';
type CustomLinkProps = {
href: string;
children: ReactNode;
};
export function CustomLink({ href, children }: CustomLinkProps) {
const router = useRouter();
const clearCacheAndPush = (e: React.MouseEvent<HTMLElement>) => {
e.preventDefault();
startTransition(() => {
router.refresh();
router.push(href);
});
};
return (
<a href="#" onClick={clearCacheAndPush}>
{children}
</a>
);
}And replaced all the uses of
Link with this one, but still doesn't update the content.Appreciate the help though!