Integrating Astro.js Starlight Documentation into a Next.js Project Using Proxies


Shoutout to the Astro and Starlight team for helping me get this right.

This guide provides step-by-step instructions on how to integrate Astro.js Starlight documentation into a Next.js project using proxies.

Astro Starlight is an excellent documentation template. However, if your main marketing site is running on Next.js, you may wonder how to integrate the two seamlessly. Let's explore how to do this.

Setting Up a Proxy in Next.js

Begin by configuring Next.js to proxy requests to our Astro docs.

Open next.config.js and add a rewrites() method that returns an array of rewrite rules:

module.exports = {
  async rewrites() {
    return [
      { 
        source: "/docs", 
        destination: "http://localhost:3001/docs" 
        
      },
      {
        source: "/docs/:path*",
        destination: "http://localhost:3001/docs/:path*",
      },
    ];
  },
  trailingSlash: false,
};

The first rule handles the /docs route, while the second rule handles any paths under /docs.

Setting trailingSlash to false prevents rewrite loops when deploying. This isn't necessary when working locally but becomes critical when deploying to a host like Vercel.

Configuring the Base Path in Astro

Having set up the proxy, we need to specify to Astro that the docs live under /docs.

Open astro.config.mjs and set a base path:

export default defineConfig({ 
  base: "/docs" 
});

This prepends /docs to all generated URLs.

Setting the Output Directory

We also need to specify the output directory to contain the assets:

export default defineConfig({ 
  base: "/docs" ,
  outDir: "./dist/docs"
});

This ensures static files do not end up in the site root, as we want to serve these at /docs.

Adding Canonical Links

Lastly, add canonical links to prevent issues with duplicate content:

export default defineConfig({ 
  base: "/docs" ,
  outDir: "./dist/docs",
  site: "https://my-site.com"
});

Starlight components will automatically add <link rel="canonical"> tags pointing to the main site.

Conclusion

You get best in class docs AND solid SEO practices. Who could ask for more?

I highly recommend giving both Astro and Starlight a try. It’s really great for content sites and docs. And the great thing is, it can be integrated with your main sites without big rewrites.