0
0
NextJSframework~15 mins

Script component for third-party scripts in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Next.js Script Component for Third-Party Scripts
📖 Scenario: You are building a Next.js website that needs to include a third-party analytics script. To keep your site fast and safe, you want to load this script properly using Next.js features.
🎯 Goal: Learn how to add a third-party script using the Next.js Script component to load it safely and efficiently.
📋 What You'll Learn
Create a Next.js functional component named Analytics
Import the Script component from next/script
Add a Script component with the exact src URL https://example.com/analytics.js
Set the strategy prop of Script to afterInteractive
Add an id prop with value analytics-script to the Script component
💡 Why This Matters
🌍 Real World
Many websites need to include third-party scripts like analytics, chat widgets, or ads. Using Next.js Script component helps load these scripts safely and efficiently.
💼 Career
Knowing how to properly add third-party scripts in Next.js is important for frontend developers to optimize site performance and maintain security.
Progress0 / 4 steps
1
Create the Analytics component and import Script
Create a functional component called Analytics in Next.js. Import the Script component from next/script at the top.
NextJS
Need a hint?

Use import Script from 'next/script' and define function Analytics().

2
Add the Script component with src URL
Inside the Analytics component, return a Script component with the src prop set to "https://example.com/analytics.js".
NextJS
Need a hint?

Use <Script src="https://example.com/analytics.js" /> inside the return.

3
Set the strategy prop to afterInteractive
Modify the Script component to include the strategy prop with the value "afterInteractive".
NextJS
Need a hint?

Add strategy="afterInteractive" inside the Script tag.

4
Add an id prop to the Script component
Add an id prop with the value "analytics-script" to the Script component inside the Analytics component.
NextJS
Need a hint?

Add id="analytics-script" inside the Script tag.