Incrementally Adopting Next.js

    Next.js has been designed for gradual adoption. With Next.js, you can continue using your existing code and add as much (or as little) React as you need. By starting small and incrementally adding more pages, you can prevent derailing feature work by avoiding a complete rewrite.

    The first strategy is to configure your server or proxy such that, everything under a specific subpath points to a Next.js app. For example, your existing website might be at , and you might configure your proxy such that example.com/store serves a Next.js e-commerce store.

    Using , you can configure your Next.js application’s assets and links to automatically work with your new subpath /store. Since each page in Next.js is its own standalone route, pages like pages/products.js will route to example.com/store/products in your application.

    The second strategy is to create a new Next.js app that points to the root URL of your domain. Then, you can use rewrites inside next.config.js to have some subpaths to be proxied to your existing app.

    For example, let’s say you created a Next.js app to be served from example.com with the following next.config.js. Now, requests for the pages you’ve added to this Next.js app (e.g. /about if you’ve added pages/about.js) will be handled by Next.js, and requests for any other route (e.g. /dashboard) will be proxied to proxy.example.com.

    1. // next.config.js
    2. module.exports = {
    3. async rewrites() {
    4. return {
    5. // and static files we proxy any other requests
    6. fallback: [
    7. {
    8. source: '/:path*',
    9. destination: `https://proxy.example.com/:path*`,
    10. },
    11. ],
    12. // For versions of Next.js < v10.1 you can use a no-op rewrite instead
    13. return [
    14. // we need to define a no-op rewrite to trigger checking
    15. // all pages/static files before we attempt proxying
    16. source: '/:path*',
    17. destination: '/:path*',
    18. },
    19. {
    20. source: '/:path*',
    21. destination: `https://proxy.example.com/:path*`,
    22. },
    23. ]
    24. }

    To learn more about rewrites, take a look at our .

    Next.js and make it straightforward to adopt micro frontends and deploy as a monorepo. This allows you to use to adopt new applications incrementally. Some benefits of micro-frontends:

    • Smaller, more cohesive and maintainable codebases.
    • More scalable organizations with decoupled, autonomous teams.
    • The ability to upgrade, update, or even rewrite parts of the frontend in a more incremental fashion.

    To learn more, read about subpaths and or deploy a Next.js monorepo.