When you set a router.base via the nuxt.config.js and deploy to Cloudflare Workers, static assets throw a 404.
After some investigations, I think I found the reason for this behavior. While the router itself is updated, the path of the assets (.output/public/_nuxt/) is unchanged. Thus, the files are uploaded without router base integration.
My naive workaround was a nitro hook that alters the behavior and moves the _nuxt folder to create a structure including the router base:
import path from 'upath'
import { ensureDir, writeFile as fseWriteFile, move } from 'fs-extra'
import consola from 'consola'
async function writeFile(file, contents) {
await ensureDir(path.dirname(file))
await fseWriteFile(file, contents, 'utf-8')
}
async function moveFilesIfRouterBase(output) {
const CUSTOM_BASE = process.env.NUXT_ROUTER_BASE // Get the router base somehow
const hasCustomRouterBase = CUSTOM_BASE !== '/'
if (!hasCustomRouterBase) {
consola.info('No custom router base given.')
return
}
const outputPath = path.resolve(output.dir)
const PUBLIC_FOLDER_NAME = 'public'
const ASSET_FOLDER_NAME = '_nuxt'
const assetFolder = path.join(
outputPath,
PUBLIC_FOLDER_NAME,
ASSET_FOLDER_NAME
)
const customRouterBaseFolder = path.join(
outputPath,
PUBLIC_FOLDER_NAME,
CUSTOM_BASE
)
const newAssetFolder = path.join(customRouterBaseFolder, ASSET_FOLDER_NAME)
await ensureDir(customRouterBaseFolder)
await move(assetFolder, newAssetFolder)
consola.success(`Moved files to ${newAssetFolder}`)
}
export default {
//...
nitro: {
hooks: {
async 'nitro:compiled'({ output, _nuxt }) {
await moveFilesIfRouterBase(output)
await originalPreset(output) // Content from the actual CF preset)
}
}
I'd be happy to add a PR adding this or a more sophisticated solution to the CF preset ☺️
Update: Also applies to favicon and content from /static, so not only _nuxt
When you set a
router.basevia thenuxt.config.jsand deploy to Cloudflare Workers, static assets throw a 404.After some investigations, I think I found the reason for this behavior. While the router itself is updated, the path of the assets (
.output/public/_nuxt/) is unchanged. Thus, the files are uploaded without router base integration.My naive workaround was a nitro hook that alters the behavior and moves the
_nuxtfolder to create a structure including the router base:I'd be happy to add a PR adding this or a more sophisticated solution to the CF preset☺️
Update: Also applies to
faviconand content from/static, so not only_nuxt