Using exportPathMap in Next.js for Route Management

nextjs export path map
25 November 2024

If you are looking for a way to better control the routes of pages in Next.js applications, the exportPathMap is an example of this. This feature allows you to specify your own static routes directly. With this feature, you can prepare routes and pages before the build time.

Assuming you have a site built on the basis of pre-defined data and want to generate a limited set of pages statically. This is when exportPathMap comes in handy.

One of the advantages of using exportPathMap is that you can fully define the routes and methods of access to different pages yourself. Also, with this method, you can exert more control over the server resources and reduce loading time.

Although this feature is powerful, you must keep in mind that routes that are not specified in exportPathMap will be dynamic and may not be accessible at runtime, providing you with the option of having dynamic pages as well.

Sample Code for Using exportPathMap


module.exports = {
  exportPathMap: async function (defaultPathMap) {
    return {
      '/': { page: '/' },
      '/about': { page: '/about' },
      '/post/1': { page: '/post', query: { id: '1' } },
      '/post/2': { page: '/post', query: { id: '2' } }
    };
  }
};

Code Explanation Line by Line

module.exports: Code that is being published is a specific configuration for use in Next.js.
exportPathMap: This function is used to define the static routes that are specified asynchronously.
defaultPathMap: This parameter holds the default route map generated by Next.js automatically.
return: We are returning our custom routes back to Next.js.
'/': The main route of the site that corresponds to the homepage.
'/about': A route that leads to the about page.
'/post/1' and '/post/2': Routes pointing to post pages with specific query parameters for identifying the post number.

FAQ

?

How can I define custom routes with exportPathMap?

?

Does using exportPathMap affect dynamic pages?