Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When using server middlewares content type disappears inside managementUI #4

Open
0x77dev opened this issue Mar 25, 2024 · 0 comments

Comments

@0x77dev
Copy link

0x77dev commented Mar 25, 2024

When using a custom middleware (in my scenario for auth purposes) in the ~/server folder, managementUI breaks. It seems like the content type is not set correctly, causing pages to show plain text instead of HTML and etc.

To reproduce just place any middleware in server, like for example:

import { getServerSession } from "#auth"

export default defineEventHandler(async (event) => {
  const url = getRequestURL(event)
  if (!url.pathname.startsWith('/_concierge')) return

  const auth = await getServerSession(event)

  if (!auth) {
    return sendRedirect(event, '/auth/signin?callbackUrl=' + encodeURIComponent(url.pathname + url.search))
  }
})

Bad Workaround in my scenario looks like this (seriously, don't do this):

import { getServerSession } from "#auth"

export default defineEventHandler(async (event) => {
  const url = getRequestURL(event)
  if (!url.pathname.startsWith('/_concierge')) return

  const auth = await getServerSession(event)

  if (!auth) {
    return sendRedirect(event, '/auth/signin?callbackUrl=' + encodeURIComponent(url.pathname + url.search))
  }

  // set appropriate headers for files, since it is broken by middleware
  // TODO: remove this hack
  const contentMap = {
    'css': 'text/css',
    'js': 'text/javascript',
    'html': 'text/html',
    'json': 'application/json',
    'svg': 'image/svg+xml',
  }

  if (url.pathname.startsWith('/_concierge/api')) {
    setResponseHeaders(event, {
      'Content-Type': 'application/json',
    })
  } else {
    const type = url.pathname.split('.').pop() || 'html'
    const customContentType = contentMap[type as keyof typeof contentMap] || 'text/html'
    setResponseHeaders(event, {
      'Content-Type': customContentType,
    })
  }
})
@0x77dev 0x77dev changed the title When using server middlewares content type disappears When using server middlewares content type disappears inside managementUI Mar 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant