Non-200 Response

At times it is necessary to respond with HTTP status codes other than 200. In such cases, response handler is the place to determine what status code should be returned.

Assume this file layout.

src/
└── routes/
    └── product/
        └── [skuId]/
            └── index.tsx     # https://example.com/product/1234

404 - Not Found

Let's say that a user does a request to an invalid skuId such as https://example.com/product/999. In this case, we would like to return a 404 HTTP status code and render a 404 page. The place where we determine if the request is valid or not is in the request handler by looking into the database. Even if the response is non-200, the component still gets a chance to render a page (Except in the redirect case.)

// File: src/routes/product/[skuId]/index.tsx
import { component$ } from '@builder.io/qwik';

type EndpointData = ProductData | null;

interface ProductData {
  skuId: string;
  price: number;
  description: string;
}
export const onGet: RequestHandler<EndpointData> = async ({ params, response }) => {
  const product = await loadProductFromDatabase(params.skuId);

  if (!product) {
    // Product data not found
    // but the data is still given to the renderer to decide what to do
    response.status = 404;
    return null;
  } else {
    // ...
  }
};

export default component$(() => {
  const resource = useEndpoint<typeof onGet>(); //equivalent to useEndpoint<EndpointData>

  if (resource.state == 'resolved' && !resource.resolved) {
    // Early return for 404
    return <div>404: Product not found!!!</div>;
  }

  // Normal rendering
  return (
    <Resource
      value={resource}
      onPending={() => <div>Loading...</div>}
      onError={() => <div>Error</div>}
      onResolved={() => (
        <>
          <h1>Product: {product.productId}</h1>
          <p>Price: {product.price}</p>
          <p>{product.description}</p>
        </>
      )}
    />
  );
});
Made with ❤️ by