Problem
I have a Next.js application where I'm dynamically loading portfolio templates based on user preferences. While the functionality works, I noticed in the developer console that all template files are being fetched, even though only one template is needed at a time.
Current Implementation
I have a dynamic route [username] that loads user data and their chosen template:
// app/[username]/page.tsx
import { notFound } from "next/navigation";
import data from "@/public/FakeData.json"
const users = data.users;
export default async function userPortfolio({ params }: { params: { username: string } }) {
const user = users.filter((u)=>{
return u.username == params.username;
}).at(0);
if (!user) {
return notFound();
}
let userTemplate = user.template;
// This loads all template files even though we only need one
const TemplatePage = (await import(`@/components/Templates/${userTemplate}/${userTemplate}_Portfolio`)).default;
return (
<TemplatePage userDetails={user} />
);
}
My template files are structured like this:
components/
Templates/
Marc/
Marc_Portfolio.jsx
Rahul/
Rahul_Portfolio.tsx
Expected Behavior
When a user visits /james123 and their template is "Marc", only the Marc template files should be fetched, not the Rahul template files.
Current Behavior
When checking the Network tab in Chrome DevTools, I can see that files from all templates are being fetched, even though only one template is being used.
Question
How can I optimize the dynamic imports to only fetch the specific template files that are needed, without loading other template files?
Additional Context
- Using Next.js 15+ with App Router
- Templates are React components with their own CSS and component files
- Each user in the data has a
templateproperty that specifies which template to use
What I've Tried
I've attempted using dynamic imports with template strings, but this seems to cause Next.js to include all possible template files in the bundle.