Docs: Add documentation for next/third-parties (#57345)

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
This commit is contained in:
Houssein Djirdeh 2023-10-25 23:07:18 -07:00 committed by GitHub
parent f171cf4143
commit 7bee486f7c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 297 additions and 161 deletions

View file

@ -0,0 +1,288 @@
---
title: Third Party Libraries
description: Optimize the performance of third-party libraries in your application with the `@next/third-parties` package.
---
{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}
**`@next/third-parties`** is a library that provides a collection of components and utilities that
improve the performance and developer experience of loading popular third-party libraries in your
Next.js application.
> **Good to know**: `@next/third-parties` is a new **experimental** library that is still under
> active development. We're currently working on adding more third-party integrations.
All third-party integrations provided by `@next/third-parties` have been optimized for performance
and ease of use.
## Getting Started
To get started, you must install the `@next/third-parties` library:
```bash filename="Terminal"
npm install @next/third-parties
```
## Google Third-Parties
All supported third-party libraries from Google can be imported from `@next/third-parties/google`.
### Google Tag Manager
The `GoogleTagManager` component can be used to instantiate a [Google Tag
Manager](https://developers.google.com/maps/documentation/embed/embedding-map) container to your
page. By default, it fetches the original inline script after hydration occurs on the page.
<AppOnly>
To load Google Tag Manager for all routes, include the component directly in your root layout:
```tsx filename="app/layout.tsx" switcher
import { GoogleTagManager } from '@next/third-parties/google'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
<GoogleTagManager gtmId="GTM-XYZ" />
</html>
)
}
```
```jsx filename="app/layout.js" switcher
import { GoogleTagManager } from '@next/third-parties/google'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
<GoogleTagManager gtmId="GTM-XYZ" />
</html>
)
}
```
</AppOnly>
<PagesOnly>
To load Google Tag Manager for all routes, include the component directly in your custom `_app`:
```jsx filename="pages/_app.js"
import { GoogleTagManager } from '@next/third-parties/google'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<GoogleTagManager gtmId="GTM-XYZ" />
</>
)
}
```
</PagesOnly>
To load Google Tag Manager for a single route, include the comopnent in your page file:
<AppOnly>
```jsx filename="app/page.js"
import { GoogleTagManager } from '@next/third-parties/google'
export default function Page() {
return <GoogleTagManager gtmId="GTM-XYZ" />
}
```
</AppOnly>
<PagesOnly>
```jsx filename="pages/index.js"
import { GoogleTagManager } from '@next/third-parties/google'
export default function Page() {
return <GoogleTagManager gtmId="GTM-XYZ" />
}
```
</PagesOnly>
#### Sending Events
The `sendGTMEvent` function can be used to track user interactions on your page by sending events
using the `dataLayer` object. For this function to work, the `<GoogleTagManager />` component must be
included in either a parent layout, page, or component, or directly in the same file.
<AppOnly>
```jsx filename="app/page.js"
'use client'
import { sendGTMEvent } from '@next/third-parties/google'
export function EventButton() {
return (
<div>
<button
onClick={() => sendGTMEvent({ event: 'buttonClicked', value: 'xyz' })}
>
Send Event
</button>
</div>
)
}
```
</AppOnly>
<PagesOnly>
```jsx filename="pages/index.js"
import { sendGTMEvent } from '@next/third-parties/google'
export function EventButton() {
return (
<div>
<button
onClick={() => sendGTMEvent({ event: 'buttonClicked', value: 'xyz' })}
>
Send Event
</button>
</div>
)
}
```
</PagesOnly>
Refer to the [Tag Manager](https://developers.google.com/tag-platform/tag-manager/datalayer)
documentation to learn about the different variables and events that can be passed into the
function.
#### Options
Options to pass to the Google Maps Embed. For a full list of options, read the [Google Map Embed
docs](https://developers.google.com/maps/documentation/embed/embedding-map).
| Name | Type | Description |
| --------------- | -------- | ------------------------------------------------------------------------------- |
| `gtmId` | Required | Your GTM container id. |
| `dataLayer` | Optional | Data layer array to instantiate the container with. Defaults to an empty array. |
| `dataLayerName` | Optional | Name of the data layer. Defaults to `dataLayer`. |
| `auth` | Optional | Value of authentication parameter (`gtm_auth`) for environment snippets. |
| `preview` | Optional | Value of preview parameter (`gtm_preview`) for environment snippets. |
### Google Maps Embed
The `GoogleMapsEmbed` component can be used to add a [Google Maps
Embed](https://developers.google.com/maps/documentation/embed/embedding-map) to your page. By
default, it uses the `loading` attribute to lazy-load the embed below the fold.
<AppOnly>
```jsx filename="app/page.js"
import { GoogleMapsEmbed } from '@next/third-parties/google'
export default function Page() {
return (
<GoogleMapsEmbed
apiKey="XYZ"
height={200}
width="100%"
mode="place"
q="Brooklyn+Bridge,New+York,NY"
/>
)
}
```
</AppOnly>
<PagesOnly>
```jsx filename="pages/index.js"
import { GoogleMapsEmbed } from '@next/third-parties/google'
export default function Page() {
return (
<GoogleMapsEmbed
apiKey="XYZ"
height={200}
width="100%"
mode="place"
q="Brooklyn+Bridge,New+York,NY"
/>
)
}
```
</PagesOnly>
#### Options
Options to pass to the Google Maps Embed. For a full list of options, read the [Google Map Embed
docs](https://developers.google.com/maps/documentation/embed/embedding-map).
| Name | Type | Description |
| ----------------- | -------- | --------------------------------------------------------------------------------------------------- |
| `apiKey` | Required | Your api key. |
| `mode` | Required | [Map mode](https://developers.google.com/maps/documentation/embed/embedding-map#choosing_map_modes) |
| `height` | Optional | Height of the embed. Defaults to `auto`. |
| `width` | Optional | Width of the embed. Defaults to `auto`. |
| `style` | Optional | Pass styles to the iframe. |
| `allowfullscreen` | Optional | Property to allow certain map parts to go full screen. |
| `loading` | Optional | Defaults to lazy. Consider changing if you know your embed will be above-the-fold. |
| `q` | Optional | Defines map marker location. _This may be required depending on the map mode_. |
| `center` | Optional | Defines center of the map view. |
| `zoom` | Optional | Sets initial zoom level of the map. |
| `maptype` | Optional | Defines type of map tiles to load. |
| `language` | Optional | Defines the language to use for UI elements and for the display of labels on map tiles. |
| `region` | Optional | Defines the appropriate borders and labels to display, based on geo-political sensitivities. |
### YouTube Embed
The `YouTubeEmbed` component can be used to load and display a YouTube embed. This component loads
faster by using [`lite-youtube-embed`](https://github.com/paulirish/lite-youtube-embed) under the
hood.
<AppOnly>
```jsx filename="app/page.js"
import { YouTubeEmbed } from '@next/third-parties/google'
export default function Page() {
return <YouTubeEmbed videoid="ogfYd705cRs" height={400} params="controls=0" />
}
```
</AppOnly>
<PagesOnly>
```jsx filename="pages/index.js"
import { YouTubeEmbed } from '@next/third-parties/google'
export default function Page() {
return <YouTubeEmbed videoid="ogfYd705cRs" height={400} params="controls=0" />
}
```
</PagesOnly>
#### Options
| Name | Type | Description |
| ----------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `videoid` | Required | YouTube video id. |
| `width` | Optional | Width of the video container. Defaults to `auto` |
| `height` | Optional | Height of the video container. Defaults to `auto` |
| `playlabel` | Optional | A visually hidden label for the play button for accessibility. |
| `params` | Optional | The video player params defined [here](https://developers.google.com/youtube/player_parameters#Parameters). <br> Params are passed as a query param string. <br> Eg: `params="controls=0&start=10&end=30"` |
| `style` | Optional | Used to apply styles to the video container. |

View file

@ -0,0 +1,7 @@
---
title: Third Party Libraries
description: Optimize the performance of third-party libraries in your application with the `@next/third-parties` package.
source: app/building-your-application/optimizing/third-party-libraries
---
{/* DO NOT EDIT. The content of this doc is generated from the source above. To edit the content of this page, navigate to the source page in your editor. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}

View file

@ -1 +0,0 @@
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=

View file

@ -1,36 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View file

@ -1,35 +0,0 @@
## Example app using Google Tag Manager
This example shows how to use Next.js along with Google Tag Manager. [`pages/_document.js`](pages/_document.js) is used to inject [base code](https://developers.google.com/tag-manager/quickstart). [`pages/_app.js`](pages/_app.js) is used to track route changes and send page views to Google Tag Manager.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-google-tag-manager&project-name=with-google-tag-manager&repository-name=with-google-tag-manager)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-google-tag-manager with-google-tag-manager-app
```
```bash
yarn create next-app --example with-google-tag-manager with-google-tag-manager-app
```
```bash
pnpm create next-app --example with-google-tag-manager with-google-tag-manager-app
```
Next, copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
Set the `NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID` variable in `.env.local` to match your Google Tag Manager ID.
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).

View file

@ -1,8 +0,0 @@
export const GTM_ID = process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID
export const pageview = (url) => {
window.dataLayer.push({
event: 'pageview',
page: url,
})
}

View file

@ -1,13 +0,0 @@
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}

View file

@ -1,36 +0,0 @@
import { useEffect } from 'react'
import Script from 'next/script'
import { useRouter } from 'next/router'
import { GTM_ID, pageview } from '../lib/gtm'
function MyApp({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
router.events.on('routeChangeComplete', pageview)
return () => {
router.events.off('routeChangeComplete', pageview)
}
}, [router.events])
return (
<>
{/* Google Tag Manager - Global base code */}
<Script
id="gtag-base"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer', '${GTM_ID}');
`,
}}
/>
<Component {...pageProps} />
</>
)
}
export default MyApp

View file

@ -1,22 +0,0 @@
import { Html, Head, Main, NextScript } from 'next/document'
import { GTM_ID } from '../lib/gtm'
export default function Document() {
return (
<Html>
<Head />
<body>
<noscript>
<iframe
src={`https://www.googletagmanager.com/ns.html?id=${GTM_ID}`}
height="0"
width="0"
style={{ display: 'none', visibility: 'hidden' }}
/>
</noscript>
<Main />
<NextScript />
</body>
</Html>
)
}

View file

@ -1,10 +0,0 @@
export default function Home() {
return (
<div>
<h1>
Go to `pages/_app.js` and `pages/_document.js` to see how you can add
Google Tag Manager to your app
</h1>
</div>
)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View file

@ -19,4 +19,6 @@ export type YouTubeEmbed = {
width?: number
videoid: string
playlabel?: string
params?: string
style?: string
}