Sitemap

Load animated GLTF models in Next.js app with Three.js

3 min readDec 14, 2020
Press enter or click to view image in full size
Animated drone loaded with GLTF loader in Next.js app

Drone by Willy Decarpentrie downloaded for free from Setchfab.

Three.js is marching with song through the world of web and browser game development enriching its visual part with a stunning 3D animation and bringing a new depth to interactions. It is a relatively easy to implement, beautiful and incredibly flexible tool. The release of React renderer react-three-fiber brought a whole new dimension to organizing your work with Three.js. There is one ingredient missing though. If you want to build not only a beautiful, but also a SEO-friendly application, you have to turn your gaze to ssr, which brings a few small problems we are going to solve.

Creating a Next.js app

Let’s start with installing dependencies

$ npm i — save next react react-three-fiber three drei react react-dom

$ npm i — save-dev @types/next @types/node @types/three typescript @types/react @types/react-dom

Then let’s config tsconfig.json to use typescript

And create the index.tsx file in pages folder where we import Canvas from react-three-fiber

Add your model with a texture in the public folder

Add some light 💡

Then we create Light.tsx file in components folder. All configurations are the result of experimentations, feel free to tweak it as you like.

Load model

And finally let’s create Model.tsx in the components folder and load model with gltf loder. To run loader during runtime let’s wrap our loader in useEffect hooker. If you try to load the model without useEffect you might face a problem with xmlhttp because Next.js will try to load model on the server side, which we do not want to do.

Now it’s time to import both components in our index.tsx and try to run the application to see what will happen.

After we run the app we see… not quite what we expected

What does it mean?

It means that Next.js does not automatically transpile modules and we need to teach it to do so. For that purpose we will use next-transpile-modules plugin

$ npm i -next-transpile-modules

And create next.config.js file in the root directory of the app and configure it to transpile our three module.

Now lets try to run again.

Press enter or click to view image in full size

Yay! It is working!

Note: if you are using an older version of Next.js you have to also add gltf loder to your webpack as in the picture below.

Now you are ready to submerge into the overwhelming world of 3D animation and enjoy all benefits of server-side rendering.

Full project repo: https://github.com/RijelEk/next-three-example

Liked the story? Consider support: https://ko-fi.com/oslavtichie

--

--

Responses (3)