Astro: Disable Admin UI Routes in Production

🙏

This is a community contribution from Florian Lefebvre — thank you Florian!

When using the local strategy, you may want to disable access to the /keystatic routes in production.

Here's how you can prevent access to (and indexing of) those routes if you're using the Astro framework.

Adding redirects

You can redirect visits to the /keystatic route in production with Astro.redirect:

---
// src/pages/keystatic/[...params].astro
import { Keystatic } from '../../../keystatic.page'

export const prerender = false

+ if (import.meta.env.MODE === 'production') {
+   return Astro.redirect('/')
+ }
---

<Keystatic client:only />

You will need to do the same for the api/keystatic routes:

// src/pages/api/keystatic/[...params].ts
import { makeHandler } from '@keystatic/astro/api'
import keystaticConfig from '../../../../keystatic.config'
+ import { APIContext } from 'astro'

- export const all = makeHandler({
-  config: keystaticConfig,
- })

+ export const all = ({ ...params }: APIContext) => {
+  if (import.meta.env.MODE === 'production') {
+    return params.redirect('/', 307)
+  }

+  return makeHandler({
+    config: keystaticConfig,
+  })(params)
+}


export const prerender = false

Excluding routes from sitemap

If you're using @astrojs/sitemap, you can exclude those routes as well:

// astro.config.mjs
import { defineConfig } from 'astro/config'
import sitemap from '@astrojs/sitemap';

export default defineConfig({
  integrations: [
+     sitemap({
+       filter: (page) => !page.includes("keystatic"),
+     });
  ]
})