Basic explanation about the next.config.js file
Vaibhav Verma
Team Lead ★ Sr. Web/JavaScript Developer ★ JavaScript ★ TypeScript ★ React ★ Next.js ★ Node.js★ MongoDB ★ AWS
The?next.config.js?file is a critical file for nextjs. You configure lots of stuff with the?next.config.jsfile.
Understanding the?next.config.js?is essential to learning nextjs with the?next.config.js?file; adding and updating the existing configuration in nextjs is easy.
You only need to spend a little time configuring next.js; most of the config in nextjs is a copy-paste.
The default nextjs config file looks like in typescript and javascript.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
Currently, I’m discussing only those more important, and easy configurable opations , for the advanced configurations, I need some extra time to explain.
Step
Environment Variables
In the nextjs, there are two ways to add the Environment variable. The first way is?.env?file, and the second way is the?next.config.js?. It provides similar functionality to the?.env?file.
/** @type {import('next').NextConfig} */
const nextConfig = {
env: {
myCustomEnvirement: 'home pages envirement',
},
}
module.exports = nextConfig
You can access the env file?process.env.customEnvirement
export default function Home() {
return (
<h1 className={styles.title}>
Welcome to Next.js {process.env.myCustomEnvirement}
</h1>
)
Base Path
You can change the base path in nextjs, and The basePath is most useable when we deploy the nextjs app with GitHub pages. The default value of basePath is?/?(slash)
/** @type {import('next').NextConfig} */
const nextConfig = {
basePath: '/my-repo',
}
module.exports = nextConfig
Rewrites
Rewrites allow you to map an incoming request path to a different destination or path.
The simple word rewrite helps to write old source content ( javascript, css and html files) to a new destination. The most crucial thing in rewriting is not to change your URL; your URL is the same.
/** @type {import('next').NextConfig} */
const nextConfig = {
async rewrites() {
return [
{
source: '/new-rewrite-path',
destination: '/old-rewrite-path',
},
]
},
}
module.exports = nextConfig
Rewrite takes the destination URL and writes on the source path.
Redirects
Redirect the incoming request to a different path or location. Redirects are the most usable for SEO; the best redirect example is when we change the blog slug, and you can redirect the old blog slug to the new slug.
/** @type {import('next').NextConfig} */
const nextConfig = {
async redirects() {
return [
{
source: '/old-path-to',
destination: '/new-path',
permanent: true,
},
]
},
}
module.exports = nextConfig
Custom Headers
In the nextjs, You can set the custom HTTP headers easily, and you can also set the dynamic base on response.
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
source: '/',
headers: [
{
key: 'x-index',
value: 'index page',
},
],
},
{
source: '/about',
headers: [
{
key: 'x-about',
value: 'about us',
},
],
},
]
},
}
module.exports = nextConfig
Custom Page Extensions
You can add a custom page extension for nextjs; otherwise, nextjs throw an Error: The default export is not a React Component in the page.
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['mdx', 'md', 'jsx', 'js', 'tsx', 'ts'],
}
module.exports = nextConfig
CDN Support with Asset Prefix
assetPrefix configuration helps to build CDN support for your nextjs app. you can easily convert your asset folder into a CDN link.
/** @type {import('next').NextConfig} */
const isProd = process.env.NODE_ENV === 'production'
const nextConfig = {
assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined,
}
module.exports = nextConfig
assetPrefix configuration is not usable for vercel and netlify. vercel and netlify automatic config global CDN for nextjs app.
Compress
Nextjs is used gzip to compress all static and content files. You can easily enable or disable it in nextjs.
/** @type {import('next').NextConfig} */
const nextConfig = {
compress: false,
}
module.exports = nextConfig
x-powered-by
Nextjs adding an?x-powered-by?property in the header does not provide any extra layer of security for nextjs. It tells the environment or framework name.
/** @type {import('next').NextConfig} */
const nextConfig = {
poweredByHeader: false,
}
module.exports = nextConfig
领英推荐
React Strict Mode
In nextjs, you can easily enable and disable the react strict mode. React strict mode only works with development. React strict mode highlighting potential problems, identify unsafe lifecycles and legacy API errors.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
Build indicator
Build indicator helps to slow indication that tells the developer to nextjs current busy with builtin the app.
/** @type {import('next').NextConfig} */
const nextConfig = {
devIndicators: {
buildActivityPosition: 'bottom-right',
},
}
module.exports = nextConfig
Disabling ETag Generation
Nextjs use?ETag ( Entity Tag )?generation on every page by default. ETag helps to allow the Web cache to be more efficient and saves bandwidth.
/** @type {import('next').NextConfig} */
const nextConfig = {
generateEtags: false,
}
module.exports = nextConfig
Custom build directory
You can change the build a directory name according to the requirement in nextjs with the help of?next.config.jsfile. you can change or rename?.next?build folder to?build?folder with?distDir?property.
/** @type {import('next').NextConfig} */
const nextConfig = {
distDir: 'build',
}
module.exports = nextConfig
Trailing Slash
The trailing slash is not rocket science. The simple word trailing slash property adds a slash end for your URL. For example?/about?to?/about/?or?/abc?to?/abc/?.
/** @type {import('next').NextConfig} */
const nextConfig = {
trailingSlash: true,
}
module.exports = nextConfig
Ignoring ESLint
Ignore the ESlint issue during build or production time. If you build a demo app and do not take the eslint issue seriously. You can ignore it with?ignoreDuringBuilds?property set true in?next.config.js?.
/** @type {import('next').NextConfig} */
const nextConfig = {
eslint: {
dirs: ['pages','components'];
ignoreDuringBuilds: true,
},
}
module.exports = nextConfig
You can specify directories to run ESLint, and esLint successfully work with the?next lint?and?next build?command.
Ignoring TypeScript Errors
Ignoring TypeScript Error on Build or production time. You can?ignoreBuildErrors?set true if you are sure you have deployed your app with destructive code.
/** @type {import('next').NextConfig} */
const nextConfig = {
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = nextConfig
exportPathMap
exportPathMap?help to allow you to export your all path,?exportPathMap?only work with?next export?. The?next exporthelp to convert your static build to HTML.
/** @type {import('next').NextConfig} */
const nextConfig = {
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
'/about': { page: '/about' },
'/post/hello-nextjs': { page: '/post/[slug]', query: { slug: 'hello-nextjs' } },
'/post/learn-nextjs': { page: '/post/[slug]', query: { slug: 'learn-nextjs' } },
'/post/deploy-nextjs':{ page: '/post/[slug]', query: { slug: 'deploy-nextjs' } },
}
},
}
module.exports = nextConfig
Disabling HTTP Keep-Alive
Nextjs enables HTTP Keep-Alive by default with node 18 with node-fetch
To disable HTTP Keep-Alive on nextjs, open?next.config.js?and add the?httpAgentOptions?configuration option.
/** @type {import('next').NextConfig} */
const nextConfig = {
httpAgentOptions: {
keepAlive: false,
},
}
module.exports = nextConfig
Disable image unoptimized
Disabling the image is not a single option; you can also config image domain name, image format, image size, etc, with?next.config.js?file.
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
unoptimized: true
},
}
module.exports = nextConfig
Conclusion
Currently, this article is in the underwriting phase. From time to time, I update this article;
Compiling everything related to the?next.config.js?config file and writing with one article takes a lot of work. I will tell you which property and where you use it.
To write every think about the?next.config.js?configuration file, give me some time. So I can update everything in the article with a simple example.
source: https://medium.com/frontendweb/basic-explanation-about-the-next-config-js-file-eaa539e1fea3