Resolving issues with Sanity and Astro.js integration and deployment

26 replies
Last updated: Apr 24, 2024
Dear friends,I hope this message finds you well. I am currently experiencing a recurring issue with my brand new Sanity / Astro.js setup, and I would appreciate your assistance in resolving it.

Issue Description:I have set up Sanity Studio under the path
<http://mywebsite.com/studio|mywebsite.com/studio>
. The initial access and navigation work as expected, redirecting correctly to
<http://mywebsite.com/studio/structure|mywebsite.com/studio/structure>
. However, I encounter a significant problem when I refresh the page: it results in a 404 error, indicating that the page cannot be found.
Steps to Reproduce:1. Access the Sanity Studio at
<http://mywebsite.com/studio|mywebsite.com/studio>
.2. The page automatically redirects to
<http://mywebsite.com/studio/structure|mywebsite.com/studio/structure>
.3. Refresh the page at
<http://mywebsite.com/studio/structure|mywebsite.com/studio/structure>
.4. A 404 error is displayed.
I understand from community discussions that one potential workaround might involve reverting to version 2.2.1 of the software. However, considering the advancements and features introduced in the latest versions, downgrading seems like an undesirable solution. Maintaining the ability to refresh pages without encountering errors seems fundamental, and I am hoping there might be an alternative solution that allows us to utilize the latest version effectively.
Could you please advise if there is another approach or fix that could resolve this issue without needing to downgrade? Your guidance on how to maintain the stability and functionality of our current setup would be greatly appreciated.

Thank you for your time and assistance.

PS: still tried to use the 2.2.1 version of @sanity/astro and got this error :

``[vite] Error when evaluating SSR module /Users/kopp/Projects/layout-ch/astro.config.mjs: |- TypeError: __vite_ssr_import_4__.default is not a function``

So this is super frustrating, barely done anything with Sanity and already stuck
:melting_face:
AI Update

I understand your frustration - this is a common routing issue when embedding Sanity Studio in Astro projects. The 404 error on refresh happens because Astro needs to properly handle the Studio's client-side routing.

The Root Cause

When you embed Sanity Studio at /studio, it's a single-page application that handles its own routing client-side. When you navigate to /studio/structure, Astro initially serves the Studio correctly, but on refresh, Astro's server tries to find a file at that path and returns 404 because it doesn't exist as a static route.

The Solution

You need to configure Astro to properly serve the Studio for all /studio/* paths. Here's how:

1. Update your astro.config.mjs:

import { defineConfig } from 'astro/config';
import { sanityIntegration } from '@sanity/astro';
import vercel from '@astrojs/vercel/serverless';

export default defineConfig({
  integrations: [
    sanityIntegration({
      projectId: 'your-project-id',
      dataset: 'production',
      useCdn: false,
      studioBasePath: '/studio'
    })
  ],
  output: 'hybrid', // or 'server' - important for Studio routing
  adapter: vercel()
});

The key is setting output: 'hybrid' or output: 'server' rather than output: 'static'. This ensures Astro can handle the dynamic routing the Studio needs. I can see from the community discussion that this configuration works well with @sanity/astro.

2. If deploying to Vercel:

Create or update your vercel.json in the project root:

{
  "rewrites": [
    {
      "source": "/studio/:path*",
      "destination": "/studio"
    }
  ]
}

This tells Vercel to rewrite all /studio/* requests back to /studio, allowing the Studio's client-side router to take over.

3. If deploying to Netlify:

Add to your netlify.toml:

[[redirects]]
  from = "/studio/*"
  to = "/studio"
  status = 200

About the Version Error

The __vite_ssr_import_4__.default is not a function error you encountered with v2.2.1 suggests a module import issue. This is actually a sign that downgrading isn't the right solution - you want to stay on the latest version of @sanity/astro and fix the routing configuration instead.

Additional Troubleshooting

If you're still experiencing issues after these changes:

  1. Clear your build cache: Delete .astro, node_modules, and reinstall
  2. Verify your adapter: Make sure you have the appropriate adapter installed (e.g., @astrojs/vercel or @astrojs/netlify)
  3. Check your Sanity config: Ensure your sanity.config.ts doesn't have conflicting basePath settings

The Astro quickstart documentation has more details on setting up the integration properly, and you can also check the @sanity/astro GitHub repository for issues and examples.

This should resolve your refresh 404 issues without needing to downgrade. The latest version of @sanity/astro works well with proper server-side configuration!

Can you share your
sanity.config
?
sure, here you go (also it tells me
deskTool
is deprecated) :
import { defineConfig } from "sanity";
import { deskTool } from "sanity/desk";

export default defineConfig({
    name: "layout-project", // Can be whatever
    title: "<http://Layout.ch|Layout.ch>", // Can be whatever
    projectId: 'djqak494',
    dataset: 'production',
    plugins: [deskTool()],
    schema: {
        types: [],
    },
});
Can you try adding a
basepath
like in this config?
Ah sorry, that’s in your astro config.
Dear User,
I think you'll find that your error is a result of not following the documentation step to add a line to the
env.d.ts
file that Astro creates. This is the connection for certain module use by Vite.
For the rest, 2.2.1 should do well for you -- if you've been reading the group, you'll have seen several systems of some complexity and abilities I've demonstrated with it.

It took months to get 2.2.1 as an actually stable release, and Sanity's very capable persons are engaged elsewhere at the moment, preparing another promoted release of the central software.

Advice, then, enjoy the many abilities 2.2.1 actually has...

Best on it, Grüss no longer from Basel,
Clive
import { defineConfig } from 'astro/config';
import icon from "astro-icon";
import i18n from "@astrolicious/i18n";
import vercel from "@astrojs/vercel/serverless";
import sanity from "@sanity/astro";
import react from "@astrojs/react";

// <https://astro.build/config>
export default defineConfig({
  site: '<https://www.layout.ch>',
  build: {
    inlineStylesheets: `always`
  },
  integrations: [icon({
    iconDir: "src/assets/icons"
  }),
  i18n({
    defaultLocale: "de",
    locales: ["de", "fr", "en"],
    strategy: "prefix",
    pages: {
      "/agb": {
        fr: "/cgu",
        en: "/gtc"
      },
      "/datenschutzrichtlinie": {
        fr: "/politique-de-confidentialite",
        en: "/privacy-policy"
      },
      "/impressum": {
        fr: "/mentions-legales",
        en: "/imprint"
      }
    },
    client: {
      data: true
    },
    sitemap: true
  }),
  sanity(
    {
      projectId: "djqak494",
      dataset: "production",
      // Set useCdn to false if you're building statically.
      useCdn: false,
      studioBasePath: "/studio"
    }
  ), react()],
  output: "hybrid",
  adapter: vercel()
});
This is my
astro.config.mjs

One thing that I don't get tho is, I'm following
this tutorial , so I have my
astro.config.mjs
setup, my
sanity.config.ts
setup, but where do I define the schemas? I'm deploying everything to vercel so can I just create a sanity folder next to the
src, public
folder in my astro project? Also is
hybrid
working in with 2.2.1?
The tutorial jumps over the most important part where we actually learn how to build the CMS 😄, or maybe I'm missing something...
Back to front,• yes, hybrid works just fine with 2.2.1. And buggy with 3, just a starter there.
• Vercel will work fine, once you get the rest of your basis together; also Netlify. Astro has auto-installers which even write the small code into your astro.config.ts for you.
• schemas. Those are just the same as in any Astro project. You can actually put them wherever you like, pathing to them in the astro.config. It works well to have them in a folder with an index file exporting them, that folder at the same level as your /src file in the project
User, Sanity isn't an entirely simple system. It's presumed you'd read some of the basis documentation for it, to 'get on board'.
But if you copy how you do things from the Astro example, things should turn out well.

I appreciate that you want to be precise; that comes with a little experience, as all Sanity layouts are similar, with a few variations
And yes, as I'm promoting Astro as an 'easy on-ramps' solution as Astro intends it, the tutorial could be better. There's a lot of rushing around which has its relation probably in the speed of marketing... :)
Clive, you're my saver. I've been following various tutorials and I've noticed that they often suggest setting up separate directories for Astro and Sanity, with a typical command like
npm install sanity@latest
creating a distinct structure in a separate folder called
sanity
or
studio
. However, I didn't see this approach mentioned in the latest documentation I read. Could you help clarify whether this method of setting up separate directories for Astro and Sanity is a legacy practice, or if it’s still recommended?
I want to make the most of this setup, and your expert advice is invaluable to me. Thanks again for all the help, and Grüsse aus Bern
😉
Just seen this github repo and the frontend is actually split from sanity. So I thing I got it all wrong, I have the
sanity.config.ts
in my astro project, next to the
src and public
folder....
Thank you, User, good if can help :)
I'm thinking that where people have been suggesting separate folders, that's because they're trying to use 'scaffold installers' from each package to get started. These typically don't allow there to be content in the folder already, so a common way of 'mixing' is to first install separately, then bring in from one to the other. Which can get complicated sometimes...

With Sanity and Astro, you really don't need to do this. Astro is just one 'integration' package from Sanity, installed via
npm i @sanity/astro@2.2.1
.
Then you add it as one more integration in your astro.config. The form for 2.2.1 is like this:


import { sanityIntegration } from "@sanity/astro";
...
export defineConfig({
  integrations: [
    sanityIntegration(sanityConfig),
    ...
  ],
  ...
})

sanityConfig
is usually just your client settings for Sanity, as you'll have seen them, and is usually just be written there or in the file.
No other installs, separate or otherwise, are needed :)
...
wow that's good to here, so the way it's done in this repo is not needed right?
... on that 'Example files' repo found...that's really of date and I'd just ignore it.
Keep things simple, as mentioned, and all should go well. I'm thinking of where you can find an example, as the original for 2.2.1 is covered over by the 3.x attempt.

But actually, the project on
https://github.com/sanity-io/sanity-astro is still quite close, and appropriately simple. Just follow the pattern and naming for the Astro integration import as I put above, as that's proper for 2.2.1, and not the same in 3.
One more thing you'll need to change, given you start with this unified Sanity/Astro project. It's arranged as a monorepo, which is a good form leading into future abilities as well. However, since we want to use 2.2.1 with it, we need to defeat that it's running the integration from its local source (in /packages) which would be the flawed 3 version.

To fix this, look at your package.json and find the line,
"@sanity/astro":"*",

Remove this line, then do your
npm i @sanity/astro@2.2.1
Now you'll have that line back, but with the
^2.2.1"
version properly, rather than the
"*"
which said to use the local version.
From this point, you should be ready to move on. I'll try to find if I have a copy of the original 2.2.1 project example, back if I do...
n.b. I just fixed the
npm i
statement in the original, as it missed a decimal point in
@2.2.1
so the way it's done in this repo is not needed right?
Right -- think you'll be better off without that
n.b. again, User, the way I'm sending you is the pattern all the Astro-related releases have -- they use a monorepo.
That fact isn't important unless you were using the local source for the @sanity/astro package, which we're not, by installing the package from npm.

If you're concerned about where the Studio comes from, that's brought in by @sanity/astro, which is why you don't need any separate folders. That approach I think bears from one of the patterns used at least a while ago with NextJs.
Clive, thank you so much for all of this valuable information. Do you know what the difference is between the
2.2.1
package and the
3.0.0
? A part from the bugs 😄
And one last thing, I don't wanna take too much of your time.. Do you know where I can find up to date documentation on how to do the things right?
Most welcome, User. To make it most useful, I'm just now publishing a version of the original 2.2.1 example package, modified as above, so that it uses 2.2.1 directly from npm, but keeps all that's good about the original examples.
I'll come back here with the url in GitHub, need also to make small adjustment there....
That's amazing, thank you so much for your time and help Clive.
Ok, User, here is a repository you can use to install the oriiginal @sanity/astro examples, already tuned to use the npm 2.2.1 version as described above, and with a top-level Readme which explains that, followed by the best documentation that came with the original. Perhaps a future will offer better on that :)
You can find it here:
Sanity-Astro 2.2.1, direct from Npmjs, including examples
It's up-to-date, and I tested it. As mentioned in the Readme, you can try it as original on a Sanity dataset, and then target your own, when you're ready to try the Studio.

The adapter for Vercel is already installed, and the site/s run in Hybrid, so you can see the Studio operating on npm dev, and later work out your deployment to Vercel. I will warn that this takes some learning also, due to their arrangements, but once you are confident with it, all will work well.

As said, I've used its basis for a number of interesting things...!

Best on it, User, and have patience with yourself. Everyone learns their way in with Sanity, and finds the pathway worth it...

...and most welcome
🌲
Clive
Clive, you're an absolute legend! 🎉 This is incredible, you've seriously made my day! Having this repository with the original examples and documentation is going to be a lifesaver. I can't thank you enough for taking the time to set this up and test it, especially with the 2.2.1 version and the Vercel adapter already in place.I'm really excited to dive into the examples and start experimenting. Your advice about learning Vercel deployment is spot on, and I appreciate the heads-up. Knowing that you've built some interesting things with this foundation is super inspiring!
Thanks again for everything, Clive. You're a true gem in the Sanity community!
🙏 I'll be sure to keep you posted on my progress.Best,
User
A smile, User, and give my regards to Bern -- I liked to go on the train and visit there. Much atmosphere, or as so often in Switxerland, 'many' :)
A smile back at you, Clive! I'll certainly give my regards to Bern – and to the Aare, where I spend many a happy afternoon. It must have been lovely to visit by train 🙂

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?