Multi-SPA using Next.js

With the next.config.js we can do some neat things, such as multi-SPA routing.

If you create yourself two Next.js apps, the “main” one is named home in my example and the second is a catalog and we will be able to navigate to.

Go to the next.config.js of the home app. and add the catalog changes listed below

const nextConfig = {
    reactStrictMode: true,
    async rewrites() {
        return [
            {
                source: '/:path*',
                destination: '/:path*'
            },
            {
                source: '/catalog',
                destination: 'http://localhost:3001/catalog'
            },
            {
                source: '/catalog/:path*',
                destination: 'http://localhost:3001/catalog/:path*'
            },
        ]
    }
}

in the catalog app go to it’s next.config.js and have it look like this

const nextConfig = {
    basePath:'/catalog'
}

then when you click a hyperlink to your second app it will actually appear as if it’s simply a page on the first app, with the same port.

Code is available on github as multiSpa.