Skip to content

How to conditionally return a resource based on a query parameter? #12897

Answered by sergiodxa
jcarrano asked this question in Q&A
Discussion options

You must be logged in to vote

You could return an HTML response or a plain text response

export async function loader({ request }: Route.LoaderArgs) {
  let data = await getData(request)
  let url = new URL(request.url)
  if (url.searchParams.has("text")) return plain(formatToPlainText(data))
  return html(formatToHTML(data))
}

The plain and html functions can be wrappers of new Response that sets the correct Content-Type header.

function plain(data: string, init?: ResponseInit) {
  let headers = new Headers(init?.headers)
  headers.set("Content-Type", "text/plain")
  return new Response(data, { ...init, headers })
}

function plain(data: string, init?: ResponseInit) {
  let headers = new Headers(init?.headers)
  headers

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jcarrano
Comment options

Answer selected by jcarrano
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants