#Use of google adsense script in nextjs

1 messages · Page 1 of 1 (latest)

simple idolBOT
#

Hi @ember vector. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can use the next/script component to manage third-party scripts in your application. This component ensures that your scripts are loaded and executed properly in the client-side rendered Single Page Application (SPA) environment of Next.js.

However, the next/script component is not recommended to be used in _document.tsx. Instead, you should use it in your layout, custom _app, or individual pages.

Here's an example of how you can use it in your custom _app:

import Script from 'next/script'
 
export default function MyApp({ Component, pageProps }) {
 return (
 <>
 <Component {...pageProps} />
 <Script src="<https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-276043682855748"> />
 </>
 )
}

This script will load and execute when any route in your application is accessed. Next.js will ensure the script will only load once, even if a user navigates between multiple pages.

Please note that the next/script component is designed to improve the performance and developer experience of loading third-party scripts in your Next.js application. However, the behavior of third-party scripts can vary, and some scripts may not work well in a SPA environment. If you encounter issues, you may need to reach out to the third-party script provider for support.

For more information, you can refer to the Next.js documentation on Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts) and Third Party Libraries (https://nextjs.org/docs/pages/building-your-application/optimizing/third-party-libraries#google-third-parties).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
#

@simple idol this is my _app.tsx in my /src/pages/_app.tsx

import "../../faust.config";
import React from "react";
import { useRouter } from "next/router";
import { FaustProvider } from "@faustwp/core";
import "@/styles/globals.css";
import "@/styles/index.scss";
import { AppProps } from "next/app";
import { WordPressBlocksProvider, fromThemeJson } from "@faustwp/blocks";
import blocks from "@/wp-blocks";
import { Poppins } from "next/font/google";
import SiteWrapperProvider from "@/container/SiteWrapperProvider";
import { Toaster } from "react-hot-toast";
import NextNProgress from "nextjs-progressbar";
import themeJson from "../../theme.json";

const poppins = Poppins({
subsets: ["latin"],
display: "swap",
weight: ["300", "400", "500", "600", "700"],
});

export default function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();

return (
<FaustProvider pageProps={pageProps}>
<WordPressBlocksProvider
config={{
blocks,
theme: fromThemeJson(themeJson),
}}
>
<SiteWrapperProvider {...pageProps}>
<style jsx global>{ html { font-family: ${poppins.style.fontFamily}; } }</style>
<NextNProgress color="#818cf8" />
<Component {...pageProps} key={router.asPath} />
<Toaster
position="bottom-left"
toastOptions={{
style: {
fontSize: "14px",
borderRadius: "0.75rem",
},
}}
containerClassName="text-sm"
/>
</SiteWrapperProvider>
</WordPressBlocksProvider>
</FaustProvider>
);
}

how to include the adsense script in this ?

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

You can include the AdSense script in your _app.tsx file using the next/script component. First, you need to import Script from next/script at the top of your file. Then, you can include the AdSense script inside your component, preferably just before the closing tag of your main component.

Here's how you can modify your _app.tsx to include the AdSense script:

import "../../faust.config";
import React from "react";
import { useRouter } from "next/router";
import { FaustProvider } from "@faustwp/core";
import "@/styles/globals.css";
import "@/styles/index.scss";
import { AppProps } from "next/app";
import { WordPressBlocksProvider, fromThemeJson } from "@faustwp/blocks";
import blocks from "@/wp-blocks";
import { Poppins } from "next/font/google";
import SiteWrapperProvider from "@/container/SiteWrapperProvider";
import { Toaster } from "react-hot-toast";
import NextNProgress from "nextjs-progressbar";
import themeJson from "../../theme.json";
import Script from 'next/script' // <-- Add this line

const poppins = Poppins({
  subsets: ["latin"],
  display: "swap",
  weight: ["300", "400", "500", "600", "700"],
});

export default function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();
#

return (
<FaustProvider pageProps={pageProps}>
<WordPressBlocksProvider
config={{
blocks,
theme: fromThemeJson(themeJson),
}}
>
<SiteWrapperProvider {...pageProps}>
<style jsx global>{ html { font-family: ${poppins.style.fontFamily}; } }</style>
<NextNProgress color="#818cf8" />
<Component {...pageProps} key={router.asPath} />
<Toaster
position="bottom-left"
toastOptions={{
style: {
fontSize: "14px",
borderRadius: "0.75rem",
},
}}
containerClassName="text-sm"
/>
<Script src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-276043682855748" /> {/* <-- Add this line */}
</SiteWrapperProvider>
</WordPressBlocksProvider>
</FaustProvider>
);
}


This will ensure that the AdSense script is loaded and executed when any route in your application is accessed. Next.js will ensure the script will only load once, even if a user navigates between multiple pages.

For more information, you can refer to the Next.js documentation on **Script Optimization** (<https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

No, the AdSense script will not be loaded in the <head> tag when you use the next/script component in this way. By default, the next/script component loads scripts just before the closing </body> tag.

If you want to load the script in the <head> tag, you can use the strategy property of the next/script component and set it to beforeInteractive. This will load the script before any Next.js code and before any page hydration occurs.

Here's how you can modify the script tag:

<Script 
  src="<https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-276043682855748"> 
  strategy="beforeInteractive" 
/>

However, please note that using beforeInteractive can have an impact on your page's performance because it blocks rendering until the script is loaded.

For more information, you can refer to the Next.js documentation on Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#strategy).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

You're correct. In a Single Page Application (SPA) like a Next.js application, scripts are typically loaded once when the application is first loaded. When you navigate between pages, the application doesn't perform a full page reload, so scripts aren't reloaded.

However, the next/script component in Next.js is designed to improve the loading and execution of third-party scripts in an SPA environment. When you use next/script to load a script, Next.js ensures that the script is loaded and executed properly when any route in your application is accessed.

For Google AdSense, you might need to manually request ad reloads when navigating between pages. This typically involves calling a specific function provided by the AdSense script. Unfortunately, the exact details of how to do this depend on the AdSense script and are not covered in the provided knowledge sources.

If you're having trouble getting AdSense to work properly in your Next.js application, I would recommend reaching out to Google AdSense support or checking the AdSense documentation for more information on how to use AdSense in an SPA environment.

For more information on how to use third-party scripts in Next.js, you can refer to the Next.js documentation on Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
#

@simple idol why is it not recommended to use nextjs/Script in _document.tsx ?

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The _document.tsx file in Next.js is a special file that is used to augment the application's <html> and <body> tags. It's only rendered on the server side, and client-side JavaScript does not interact with it. This means that React components outside of <Main /> will not be initialized by the browser. Therefore, adding application logic or custom CSS (like styled-jsx) in _document.tsx is not recommended.

When it comes to next/script, it's designed to improve the loading and execution of scripts in a client-side rendered environment. If you place a next/script in _document.tsx, it won't work as expected because _document.tsx is not part of the React component tree and doesn't have access to the lifecycle methods and hooks that next/script relies on to manage scripts.

Instead, next/script should be used in your layout, custom _app, or individual pages. This ensures that your scripts are loaded and executed properly in the client-side rendered environment of Next.js.

For more information, you can refer to the Next.js documentation on Custom Document (https://nextjs.org/docs/pages/building-your-application/routing/custom-document#caveats) and Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
#

@simple idol can we force a nextjs site to not behave as a SPA ?

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can configure Next.js to disable the Single Page Application (SPA) behavior by disabling file-system routing. This can be done by setting the useFileSystemPublicRoutes configuration to false in your next.config.js file.

Here's how you can do it:

module.exports = {
 useFileSystemPublicRoutes: false,
}

This configuration will disable the automatic routing based on files in the pages directory. However, please note that this only disables server-side routing based on filenames. Client-side routing may still access those paths.

When using this option, you should guard against navigation to routes you do not want programmatically. You may also wish to configure the client-side router to disallow client-side redirects to filename routes; for that refer to router.beforePopState (https://nextjs.org/docs/pages/api-reference/functions/use-router#routerbeforepopstate).

For more information, you can refer to the Next.js documentation on Disabling file-system routing (https://nextjs.org/docs/pages/building-your-application/configuring/custom-server#disabling-file-system-routing).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
# simple idol ---------------------- Yes, you can configure Next.js to disable the Single Page...

@simple idol this is my next.config.js

const { withFaust, getWpHostname } = require("@faustwp/core");

/**

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Your next.config.js file is currently configured with the withFaust function from the @faustwp/core package. This function is likely adding some additional configuration for your Next.js application to work with the Faust.js WordPress plugin.

The trailingSlash option is set to true, which means that all routes will have a trailing slash.

The experimental field is used to enable experimental features of Next.js. Currently, typedRoutes and appDir are set to false, which means these experimental features are disabled.

The images field is used to configure the Next.js Image component. The domains array lists all the domains that your application will fetch images from. The remotePatterns array is used to match remote images that should be optimized by Next.js.

If you want to disable the Single Page Application (SPA) behavior, you can add the useFileSystemPublicRoutes configuration to your next.config.js file and set it to false. Here's how you can do it:

const { withFaust, getWpHostname } = require("@faustwp/core");
#

/**


For more information, you can refer to the Next.js documentation on **Disabling file-system routing** (<https://nextjs.org/docs/pages/building-your-application/configuring/custom-server#disabling-file-system-routing>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The useFileSystemPublicRoutes configuration in next.config.js only disables the automatic routing based on files in the pages directory. It does not disable the Single Page Application (SPA) behavior of Next.js.

In a Next.js application, when you navigate between pages using the next/link component, Next.js uses client-side navigation. This means that the page transition happens in the browser, without a full page reload. This is a key characteristic of SPAs and is part of what makes Next.js so fast.

If you want to force a full page reload when navigating between pages, you would have to use standard <a> tags instead of the next/link component. However, this is generally not recommended because it can make your application slower and less responsive.

If you're trying to disable the SPA behavior for a specific reason (like a certain third-party script that doesn't work well in an SPA), there might be other solutions or workarounds that could help. If you could provide more details about the specific issue you're facing, I might be able to provide more targeted advice.

For more information, you can refer to the Next.js documentation on Routing (https://nextjs.org/docs/app/building-your-application/routing) and Custom next.config.js (https://nextjs.org/docs/pages/building-your-application/configuring/custom-server).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, if you're not using a custom server or you don't have a specific need to disable file-system routing, you can remove the useFileSystemPublicRoutes configuration from your next.config.js file.

The useFileSystemPublicRoutes configuration is typically used when you have a custom server and you want to fully control routing, or when you want to prevent automatic routing based on files in the pages directory.

If you're not in one of these situations, you can safely remove this configuration. Your Next.js application will then continue to use the default file-system based routing.

Here's how your next.config.js file would look after removing the useFileSystemPublicRoutes configuration:

const {{ withFaust, getWpHostname }} = require("@faustwp/core");
#

/**


For more information, you can refer to the Next.js documentation on **Custom `next.config.js`** (<https://nextjs.org/docs/pages/building-your-application/configuring/custom-server>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
#

@simple idol this is an adstyle from google can we add this in every page ??

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2760436828485865"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-2760436828543422"
data-ad-slot="29744478788"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can add this AdSense script to every page in your Next.js application. However, you should use the next/script component to manage the loading and execution of the script.

Here's how you can add the script to your pages:

import Script from 'next/script'

function MyComponent() {
  return (
    <>
      <Script 
        src="<https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2760436828485865"> 
        strategy="beforeInteractive" 
        crossorigin="anonymous"
        async
      />
      <ins 
        className="adsbygoogle"
        style={{ display: 'block', textAlign: 'center' }}
        data-ad-layout="in-article"
        data-ad-format="fluid"
        data-ad-client="ca-pub-2760436828543422"
        data-ad-slot="29744478788"
      />
      <Script strategy="beforeInteractive">
        {`(adsbygoogle = window.adsbygoogle || []).push({});`}
      </Script>
    </>
  )
}

In this example, the async attribute is passed as a prop to the Script component, and the strategy prop is set to beforeInteractive to load the script before any other JavaScript is executed.

The ins tag is used to specify the ad slot. The style and data-* attributes are passed as props to the ins component.

The second Script component is used to execute the inline script that initializes the ad.

Please note that this is a simplified example and you might need to adjust it based on your specific needs and the exact requirements of the AdSense script.

For more information, you can refer to the Next.js documentation on Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

You should add the AdSense script in your _app.tsx file, not in _document.tsx.

The _document.tsx file in Next.js is only rendered on the server side, and client-side JavaScript does not interact with it. Therefore, adding application logic or custom CSS (like styled-jsx) in _document.tsx is not recommended.

On the other hand, the _app.tsx file is a good place to put global layout, global CSS, or scripts that need to be included on every page.

Here's how you can add the script to your _app.tsx file:

import Script from 'next/script'
import type { AppProps } from 'next/app'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script 
        src="<https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2760436828485865"> 
        strategy="beforeInteractive" 
        crossorigin="anonymous"
        async
      />
      <ins 
        className="adsbygoogle"
        style={{ display: 'block', textAlign: 'center' }}
        data-ad-layout="in-article"
        data-ad-format="fluid"
        data-ad-client="ca-pub-2760436828543422"
        data-ad-slot="29744478788"
      />
      <Script strategy="beforeInteractive">
        {{`(adsbygoogle = window.adsbygoogle || []).push({{}});`}}
      </Script>
      <Component {...pageProps} />
    </>
  )
}

For more information, you can refer to the Next.js documentation on Custom _app (https://nextjs.org/docs/pages/building-your-application/routing/custom-app) and Script Optimization (https://nextjs.org/docs/app/building-your-application/optimizing/scripts#application-scripts).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@ember vector kapa.ai is still learning and improving, please let us know how it did by reacting below

ember vector
# simple idol ---------------------- You should add the AdSense script in your `_app.tsx` file...

@simple idol where to add this in my _app.tsx ??

import "../../faust.config";
import React from "react";
import { useRouter } from "next/router";
import { FaustProvider } from "@faustwp/core";
import "@/styles/globals.css";
import "@/styles/index.scss";
import { AppProps } from "next/app";
import { WordPressBlocksProvider, fromThemeJson } from "@faustwp/blocks";
import blocks from "@/wp-blocks";
import { Poppins } from "next/font/google";
import SiteWrapperProvider from "@/container/SiteWrapperProvider";
import { Toaster } from "react-hot-toast";
import NextNProgress from "nextjs-progressbar";
import themeJson from "../../theme.json";
import Script from "next/script";

const poppins = Poppins({
subsets: ["latin"],
display: "swap",
weight: ["300", "400", "500", "600", "700"],
});

export default function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();

return (
<FaustProvider pageProps={pageProps}>
<WordPressBlocksProvider
config={{
blocks,
theme: fromThemeJson(themeJson),
}}
>
<SiteWrapperProvider {...pageProps}>
<style jsx global>{ html { font-family: ${poppins.style.fontFamily}; } }</style>
<NextNProgress color="#818cf8" />
<Component {...pageProps} key={router.asPath} />
<Toaster
position="bottom-left"
toastOptions={{
style: {
fontSize: "14px",
borderRadius: "0.75rem",
},
}}
containerClassName="text-sm"
/>
</SiteWrapperProvider>
</WordPressBlocksProvider>
</FaustProvider>
);
}

simple idolBOT
#

Let me check the knowledge base for you. One moment! :books:

#

You can add the AdSense script at the top of the return statement in your MyApp function in _app.tsx. This ensures that the script is loaded and executed on every page of your application.

Here's how you can modify your _app.tsx file to include the AdSense script:

import "../../faust.config";
import React from "react";
import { useRouter } from "next/router";
import { FaustProvider } from "@faustwp/core";
import "@/styles/globals.css";
import "@/styles/index.scss";
import { AppProps } from "next/app";
import { WordPressBlocksProvider, fromThemeJson } from "@faustwp/blocks";
import blocks from "@/wp-blocks";
import { Poppins } from "next/font/google";
import SiteWrapperProvider from "@/container/SiteWrapperProvider";
import { Toaster } from "react-hot-toast";
import NextNProgress from "nextjs-progressbar";
import themeJson from "../../theme.json";
import Script from "next/script";

const poppins = Poppins({
  subsets: ["latin"],
  display: "swap",
  weight: ["300", "400", "500", "600", "700"],
});

export default function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();
#

return (
<>
<Script
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2760436828485865"
strategy="beforeInteractive"
crossorigin="anonymous"
async
/>
<ins
className="adsbygoogle"
style={{ display: 'block', textAlign: 'center' }}
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-2760436828543422"
data-ad-slot="29744478788"
/>
<Script strategy="beforeInteractive">
{{(adsbygoogle = window.adsbygoogle || []).push({{}});}}
</Script>
<FaustProvider pageProps={pageProps}>
<WordPressBlocksProvider
config={{
blocks,
theme: fromThemeJson(themeJson),
}}
>
<SiteWrapperProvider {...pageProps}>
<style jsx global>{ html { font-family: ${poppins.style.fontFamily}; } }</style>
<NextNProgress color="#818cf8" />
<Component {...pageProps} key={router.asPath} />
<Toaster
position="bottom-left"
toastOptions={{
style: {
fontSize: "14px",
borderRadius: "0.75rem",
},
}}
containerClassName="text-sm"
/>
</SiteWrapperProvider>
</WordPressBlocksProvider>
</FaustProvider>
</>
);
}