Encountering 404 page error after logging in with Next JS rewrites for Sanity CMS

I am currently running a Next JS site on Netlify with a Sanity CMS backend for content management. The setup involves having the front-end website on examplesite.com and accessing the Sanity Studio editor through examplesite.com/sanity.

Everything works as expected if the editor already has a login cookie, but when the editor needs to log in, upon completing the login process, the site redirects to /sanity/desk which causes Next to display a 404 page. To access the CMS, the editor then has to manually visit /sanity first before being redirected successfully to /sanity/desk without any errors.

Following the official Sanity setup guide, I have made the following adjustments in the Next configuration:

const SANITY_REWRITE = {
  source: "/sanity/:path*",
  destination:
    process.env.NODE_ENV === "development"
      ? "http://localhost:3333/sanity/:path*"
      : "/sanity/index.html",
};

const DESK_REWRITE = {
  source: "/sanity/desk",
  destination: "/sanity/index.html",
};

const withBundleAnalyzer = require("@next/bundle-analyzer")({
  enabled: process.env.ANALYZE === "true",
});

module.exports = withBundleAnalyzer({
  reactStrictMode: true,
  async rewrites() {
    return {
      beforeFiles: [SANITY_REWRITE, DESK_REWRITE],
    };
  },
  images: {
    domains: ["cdn.sanity.io"],
  },
});

Here is my sanity.json for further reference:

{
  "root": true,
  "project": {
    "name": "main-site",
    "basePath": "/sanity"
  },
  "api": {
    "projectId": "ga8f69l8",
    "dataset": "production"
  },
  "plugins": [
    "@sanity/base",
    "@sanity/components",
    "@sanity/default-layout",
    "@sanity/default-login",
    "@sanity/desk-tool",
    "@sanity/dashboard",
    "dashboard-widget-netlify"
  ],
  "env": {
    "development": {
      "plugins": ["@sanity/vision"]
    }
  },
  "parts": [
    {
      "name": "part:@sanity/base/schema",
      "path": "./schemas/schema"
    },
    {
      "name": "part:@sanity/desk-tool/structure",
      "path": "./structures/deskStructure.js"
    },
    {
      "implements": "part:@sanity/dashboard/config",
      "path": "src/dashboardConfig.js"
    }
  ]
}

The assumption was that any path after /sanity would be routed to the sanity/index.html file generated by the build command (build command included below), however, it seems to be working only for the /sanity path and not for any other additional paths.

Build command (in package.json):

{
  "scripts": {
    ...
    "prebuild": "echo 'Building Sanity to public/sanity' && cd sanity && yarn & npx @sanity/cli build ../public/sanity -y && echo 'Done'",
   ...
  },

Any assistance on this issue would be highly appreciated!

Answer №1

If you're still struggling to figure this out, here's what has been effective for me.

In your /next.config.js file:

/** @type {import('next').NextConfig} */

const STUDIO_REWRITE = {
  source: "/studio/:path*",
  destination: process.env.NODE_ENV === "development" ? 
  "http://localhost:3333/studio/:path*" : "/studio/index.html",
};

const nextConfig = {
  i18n: {
    locales: ["en"],
    defaultLocale: "en",
  },
  rewrites: async () => [STUDIO_REWRITE],
  reactStrictMode: true,
  images: {
    domains: ['cdn.sanity.io'],
  },
}

module.exports = nextConfig

And in your /netlify.toml file:

[[redirects]]
from = "/studio/*"
to = "/studio/index.html"
status = 200
force = false

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the image return an Undefined Value when clicked? Is there a solution to this issue?

Every time I click on an image, I encounter the error message "undefined." Can someone please shed some light on why this is happening and provide guidance on how to successfully retrieve and pass the value to the onclick function in this particular scen ...

Is it possible to transfer data from javascript to php through ajax?

I am attempting to extract the data speedMbps from my JavaScript code using Ajax to send the data to my PHP script, but unfortunately, I am not receiving any output. My experience with Ajax is limited to implementing auto-completion feature. <script sr ...

What is the best way to display multiple modals in a React app?

I am facing a challenge where I need to render multiple modals based on the number of items in the 'audios' property of an object. Currently, I am using the mui modal library for this functionality. Here are the variables being utilized: const ...

A recursive function in ECMAScript 6 using promises

I am currently in the process of developing a foundational class for sequelize.js. This particular class will handle the association of all related tables, with the includeFk function responsible for executing this task. The function involves the use of pr ...

Encountering a glitch while trying to launch the Angular application on Heroku

After successfully deploying my angular2 application to Heroku, I encountered an issue where the page displayed an error message saying: "An error occurred in the application and your page could not be served". The application runs smoothly when tested lo ...

The issue with updating an increment value in Mongoose has not been

I've encountered an issue while trying to increment a value and reassign it back to the key. const TopicSchema = mongoose.Schema({ count: Number }); topic.count += 2 The result I expected was 4, but instead, the value 22 is returned. Upon repea ...

Issue: The content of the text does not align with the HTML generated by the server

I'm struggling with an algorithm in next.js and encountering hydration errors. Here is the code I am using: import numbers from "../../functions/numberGenerators.js" export default function test() { ...

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

Having trouble running a basic nestjs application in Webstorm? You may encounter an error stating: "The experimental support for decorators is a functionality that might undergo changes in upcoming releases."

After following a tutorial, I used the command nest new my-nestjs-01 to create a default nestjs project. I then configured Webstorm to run typescript files by setting up some options. Now, when I open a .ts file in the editor and click at the top, the cur ...

What steps can be taken to prevent relying on static file names in the code

Currently, my web application project is being bundled using webpack. The webpack configuration in use is outlined below: const HtmlWebPackPlugin = require("html-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = requ ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

Learn how to dynamically apply a class to a table row in a dataTable based on the presence of an ID within the data,

Currently, I am utilizing dataTables to retrieve the data on the front-end. To illustrate this, I will incorporate a mock datatable in this instance. My objective is to apply highlighting/addClass to the chosen row and store it in the sessionStorage so tha ...

[Vue alert]: Issue in created function: "TypeError: Unable to assign value to undefined property"

I'm currently in the process of developing a VueJS application where I have implemented a child component called Child.vue that receives data from its parent. Child.vue export default{ props:['info'], data: function(){ ...

Eliminating repeated entries in MongoDB

Hey guys, I've been struggling for days trying to eliminate all the duplicates from my database. I attempted a solution I came across on this Link, but encountered an error message stating that forEach is not a function. I'm puzzled as to why it ...

Utilizing Node.js modules in a frontend HTML file with the help of browserify

I am encountering difficulty using a node.js module on my website with browserify. The example provided only demonstrates how to run a separate JavaScript file, not how to incorporate the node.js module within the .html file itself. This seemingly simple i ...

Ensure the footer remains fixed while scrolling

For the past day, I've been tackling a challenge with my online shop project. On the specific item's page, I want to include a fixed [add to cart] button as a footer initially, which then becomes sticky when scrolling to a certain point. You can ...

retrieve the path attribute value using SVG

Upon inspection in Chrome DevTools, the following html code was found: <path class="link" d="M0,130C65,130 65,65 130,65"></path> <path class="link" d="M0,130C65,130 65,195 130,195"></path> D ...

Setting up routes in VueJS and NodeJS Express for API integration: a comprehensive guide

My API routes always return HTML instead of JSON, despite trying numerous solutions that have all failed. Here is my current setup: // app.js const express = require("express"); const app = express(); const history = require("connect-history-api-fallback ...

Is ASP.NET capable of displaying an expandable grid view?

After searching online, I have yet to find a solution that meets my requirements. Currently, my DB view generates the following data: --------------------------------------------------- Company | Code | Total | Available | Used | Needed ---------------- ...