Back to Blog

Using the Agora Web UIKit with Next.js — Build a Video Chat App

Using the Agora Web UIKit with Next.js — Build a Video Chat App

\I’ve written about using the Agora Web UIKit to add live-streaming or video calling capabilities to your website in a previous blog post. In this blog post I’ll describe how to use the Agora Web UIKit with your Next.js web app.

We’ll use dynamic import to import the Agora SDK with Next.js (without running into the “window is not defined” error) when using server-side rendering (SSR) or static-site generation (SSG).

Let’s use the React example

When I try importing the React example component from the Agora Web UIKit repo in my Next.js app that was created using create-next-app like so:

I get the “window is not defined” error:

Build a Video Chat App 1

If we look at the call stack, we can see that the error is thrown by the Agora SDK.

Why do I see this error?

Next.js uses SSR and SSG — when the Agora library is imported (either directly or by the Agora Web UIKit), it accesses the Window object available on the browser. Next.js either pre-renders the web page on the server (SSG) or it renders the web page for each request (SSR). This causes an error as the window object isn’t accessible on the server. Hence the “window is not defined” error.

What’s the fix?

The fix is really simple: we want to import the Agora Web UIKit only when the page is rendered in the browser. You could hack around a solution using a conditional check for the window object, but Next.js offers a cleaner solution — dynamic import with no SSR.

I can now replace my Videocall import by using the dynamic() function call. The first argument takes in a function that just imports the component from our file. The second argument accepts an object where we mark ssr as false as we don’t want to include this module on the server side.

As soon as we update the Agora App ID in the Videocall component, we can get the example working. And now our Next.js web app has video calling!

Build a Video Chat App 2

Conclusion

You can check out the example Next.js Web UIKit project here. If you want a deeper dive, you can read this blog post covering the example in depth. You can also check out the Web UIKit GitHub Repo as well as the API Reference.

We have UIKits available for Android, iOS, React Native, and Flutter as well. You can check those out as well. If you have questions while using the Agora Web UIKit, I invite you to join the Agora Developer Slack community. You can ask your questions in the #web-help-me channel.

RTE Telehealth 2023
Join us for RTE Telehealth - a virtual webinar where we’ll explore how AI and AR/VR technologies are shaping the future of healthcare delivery.

Try Agora for Free

Sign up and start building! You don’t pay until you scale.
Try for Free
Get Started with Agora thumbnail