Boosting Next.js performance with Partytown

Lokman Musliu Founder and CEO of Lucky Media
Lokman Musliu

January 26, 2026 · 4 min read

Boosting Next.js performance with Partytown

Developers are always on the hunt for ways to squeeze every ounce of performance out of our web applications. Let's explore how to integrate Partytown into Next.js projects to enhance performance by moving third-party scripts to web workers, thereby freeing up the main thread for core functionalities.

What is Partytown?

Partytown is an open-source library designed to offload resource-intensive scripts, such as analytics and advertising, to a web worker. This approach enhances the performance of your website by reducing the load on the main thread.

Imagine this: you're hosting a party (your website), and everyone's having a blast. But then, a group of uninvited guests (third-party scripts like analytics and ads) crash the party, hogging all the snacks (main thread resources) and slowing everything down. Partytown is your "party bouncer"!

Benefits of using Partytown

Benefits of using Partytown

  • Performance improvement: Tests have shown significant improvements in Lighthouse performance scores.

  • Improved user experience: Faster load times contribute to a smoother user experience.

  • SEO advantages: Enhanced site speed can positively impact search engine rankings.

Implementing Partytown in Next.js

The implementation process varies depending on whether you use the Pages Router or the App Router in Next.js. Let's explore both methods.

Feature

Next.js Pages Router

Next.js App Router

Recommended

Use the Next.js Script component

Manual configuration of Partytown

Setup Complexity

Simpler and more automated

Requires manual configuration

Support

Supported experimentally

No official support; manual setup needed

Key Steps

1. Enable nextScriptWorkers
2. Install Partytown
3. Use strategy="worker"

1. Install Partytown
2. Copy library files
3. Add <Partytown/> component
4. Modify scripts

Partytown Nextjs app router and pages router

Using the Pages Router with Partytown

1. Enable Experimental Features

To enable Partytown, modify your next.config.js to include the nextScriptWorkers flag.

// next.config.js
module.exports = {
  experimental: {
    nextScriptWorkers: true,
  },
};

2. Install Partytown

Install Partytown via npm:

npm install @qwik.dev/partytown

3. Use the Script Component

Use the Next.js Script component with strategy="worker" to offload third-party scripts.

import Script from 'next/script';

export default function Home() {
  return (
    <>
      <Script src="https://example.com/analytics.js" strategy="worker" />
    </>
  );
}

Using the App Router with Partytown

1. Install Partytown

Start by installing Partytown:

npm install @builder.io/partytown

2. Copy Library Files

Modify your package.json to copy Partytown's library files to your public directory.

// package.json
"scripts": {
  "dev": "npm run partytown && next dev",
  "build": "npm run partytown && next build",
  "partytown": "partytown copylib public/~partytown"
}

Run npm run partytown once, or let it run automatically during dev and build.

3. Configure Partytown in Your Layout

In your root layout (app/layout.tsx), import and include the <Partytown/> component inside the <head> tag.

// app/layout.tsx
import { Partytown } from '@builder.io/partytown/react';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <Partytown debug={true} forward={['dataLayer.push']} />
      </head>
      <body>{children}</body>
    </html>
  );
}

4. Modify Your Third-Party Scripts

Add type="text/partytown" to your scripts to ensure they are handled by Partytown.

// Example for Google Tag Manager
<script
  type="text/partytown"
  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-XXXXXX');
    `
  }}
/>

Common pitfalls

Implementing Partytown can significantly boost performance, but there are common pitfalls to avoid:

  • Incompatible Scripts: Not all third-party scripts work well with Partytown. Scripts requiring direct DOM manipulation or synchronous execution may not function correctly.

  • CORS Issues: Scripts running in a web worker may face Cross-Origin Resource Sharing (CORS) issues. Consider using Next.js rewrites to proxy requests through your own domain.

  • Debugging Challenges: Debugging scripts in a web worker can be more complex. Enabling the debug mode with <Partytown debug={true} /> can help, but it may still require additional effort to trace issues.

  • Script Timing: Ensure that the timing of script execution aligns with your application's needs, as web worker execution is asynchronous and may introduce timing issues.

Positive outcomes of using Partytown

The Results

After successfully implementing Partytown, you can expect several positive outcomes:

  • Improved Performance Scores: Expect to see an increase in your Lighthouse performance scores, particularly in metrics related to speed and responsiveness.

  • Enhanced User Experience: Users will benefit from faster load times and smoother interactions, leading to higher satisfaction and potential increases in engagement.

  • SEO Benefits: Improved site speed can positively impact your search engine rankings, as speed is a known factor in SEO algorithms.

  • Reduced Main Thread Load: By offloading scripts to web workers, the main thread is free to handle more critical tasks, leading to overall improved application performance.

Conclusion

Partytown provides an effective solution for optimizing third-party script performance in Next.js applications. By offloading scripts to web workers, you can achieve significant performance improvements, enhancing user experience and potentially benefiting SEO.


Bring Your Ideas to Life 🚀

If you need help with a React project let’s get in touch.

Lucky Media is proud to be recognized as a leading Next.js Development Agency

FAQs

Can I use Partytown with any third-party script?

Not all scripts are compatible with Partytown, particularly those requiring direct, synchronous DOM access. Test your scripts for compatibility.

How does Partytown handle CORS issues?

CORS issues can arise due to scripts running from a web worker. A common solution is to proxy requests through your domain using Next.js rewrites.

Does Partytown affect SEO?

By improving site performance, Partytown can positively impact SEO. Ensure critical scripts like analytics are functioning correctly post-integration.

Is Partytown production-ready?

Partytown is still considered experimental, especially within newer Next.js App Router contexts. Conduct thorough testing before deploying to production.

How can I debug issues with Partytown?

Set <Partytown debug={true} /> to enable detailed console logs, which can help identify script-related issues.

Technologies

Next.js
Lokman Musliu Founder and CEO of Lucky Media
Lokman Musliu

Founder and CEO of Lucky Media

Stay up-to-date

Be updated with all news, products and tips we share!

Let’s chat

We partner with a limited number of brands each quarter to ensure senior-level attention on every project.

lokman and arlind headshots
Teamwork