Next.jsEasy
How do you configure path aliases in Next.js?
Define paths (and optionally baseUrl) in tsconfig.json or jsconfig.json, for example "@/*": ["./src/*"]. Next.js and Turbopack read these automatically, so import { db } from "@/lib/db" works without any bundler config. create-next-app sets up @/* by default.
Setup
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@ui/*": ["./src/components/ui/*"]
}
}
}
Notes
baseUrlis optional in TypeScript 5+, and paths resolve relative to the tsconfig. TypeScript 7 (supported innext buildsince 16.3) removesbaseUrl, so preferpathswith./prefixes.- Restart
next devafter changing tsconfig paths. - Aliases work in Server and Client Components, Route Handlers,
proxy.tsand CSS imports processed by the bundler.
Other tools need the same mapping
- Jest:
moduleNameMapper(or usenext/jest, which reads tsconfig paths). - Vitest:
vite-tsconfig-pathsplugin. - ESLint import plugins: a TypeScript resolver.
- Node scripts:
tsxresolves tsconfig paths.
Alternatives
package.jsonsubpath imports ("imports": { "#lib/*": "./src/lib/*" }) are a Node.js standard and work everywhere.turbopack.resolveAliasaliases packages, for example to swap a dependency.
Tip
Keep one main alias (@/). Many aliases make code harder to navigate.
Code example
tsx
1// tsconfig.json2// {3// "compilerOptions": {4// "paths": {5// "@/*": ["./src/*"],6// "@ui/*": ["./src/components/ui/*"]7// }8// }9// }1011// src/app/page.tsx12import { db } from "@/lib/db";13import { Button } from "@ui/button";14import { formatPrice } from "@/lib/format";1516export default async function Home() {17 const top = await db.product.findFirst();18 return (19 <main>20 <p>{top ? formatPrice(top.price) : "No products"}</p>21 <Button>Shop now</Button>22 </main>23 );24}2526// vitest.config.mts27// import tsconfigPaths from "vite-tsconfig-paths";28// export default defineConfig({ plugins: [tsconfigPaths(), react()] });
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.