status code 304 with code examples

Status code 304, also known as "Not Modified," is an HTTP response status code indicating that the requested resource has not been modified since the last time it was accessed by the client. Instead of returning the full resource, the server sends a 304 status code and a few headers indicating that the client can use the cached version of the resource.

This behavior is beneficial for both the client and the server, as it reduces the number of requests and server workload required to serve the same content repeatedly.

In this article, we’ll explore the details of the 304 status code, including its purpose, use cases, and code examples.

Purpose of Status Code 304

The main reason for sending a 304 status code is to reduce the number of requests the server needs to handle and to avoid unnecessary bandwidth consumption. When a client requests a resource, such as an image or a web page, the server checks whether the resource has been modified since the last time the client requested it.

If the resource has not been modified, the server sends a 304 status code, which tells the client to use its cached version of the resource. The client can then retrieve the resource from its cache, saving both bandwidth and time.

Use Case of Status Code 304

The 304 status code is used when a client needs to access a resource multiple times, but the resource's content has not changed since the last request. This case is prevalent in web applications, where the same web page or resource is requested by multiple users repeatedly.

For example, suppose a user visits a web page with a large image. The first time the user accesses the page, the image is downloaded from the server, and the client cache stores it. When the user revisits the same page again, the client sends a request to the server, but the server detects that the resource has not changed since the last request and returns a 304 status code with the necessary headers to retrieve the cached resource.

Code Examples of Status Code 304

To send a 304 Not Modified status code, the server includes the "If-None-Match" or "If-Modified-Since" header fields in the HTTP response message. The client sends these headers in the subsequent request to check if the resource has been modified since the last request.

Here is an example of how to send a 304 status code using Node.js and Express:

app.get("/", (req, res) => {
  const lastModified = new Date("2021-08-08T00:00:00Z");
  const currentTime = new Date();

  if (req.headers["if-modified-since"] && new Date(req.headers["if-modified-since"]) >= lastModified) {
    res.status(304).send();
  } else {
    res.setHeader("Last-Modified", lastModified);
    res.send("<h1>Welcome to my website</h1><img src='/image.jpg'>" + currentTime);
  }
});

In this example, we create a route to handle the root URL of the web application. We set the Last-Modified header to the date on which the resource was last modified. Then, we check if the If-Modified-Since header is present in the request headers, and its value is equal to or greater than the Last-Modified header. If this condition is true, we send a 304 status code without any body content. Otherwise, we return a response with the Last-Modified header and the current time.

Here is an example of how to send a 304 status code using PHP:

$lastModified = new DateTime("2021-08-08T00:00:00Z");
$currentDateTime = new DateTime();

if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) && strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]) >= $lastModified->getTimestamp()) {
  header("HTTP/1.1 304 Not Modified");
  exit();
} else {
  header("Last-Modified: " . $lastModified->format(DateTime::RFC2822));
  echo "<h1>Welcome to my website</h1><img src='/image.jpg'>" . $currentDateTime->format(DateTime::RFC2822);
}

In this example, we create a PHP script to handle the root URL of the web application. We set the Last-Modified header to the date on which the resource was last modified. Then, we check if the HTTP_IF_MODIFIED_SINCE header is present in the request headers, and its value is equal to or greater than the Last-Modified header. If this condition is true, we send a 304 status code without any body content. Otherwise, we return a response with the Last-Modified header and the current time.

Conclusion

The 304 status code is a useful tool for optimizing web applications and reducing bandwidth usage. By caching frequently accessed resources and using 304 status codes to avoid unnecessary requests, we can improve the performance and speed of our web applications.

In this article, we explored the purpose and use cases of the 304 status code and provided code examples in Node.js and PHP. With this knowledge, you can implement the 304 status code in your web applications and improve their performance.

I can expand on the previously discussed topic.

Let's start with the purpose of the 304 status code. In addition to reducing the number of requests and server workload required to serve the same content repeatedly, it also helps to improve the user experience. When the client receives a 304 status code, it knows that the resource is still up to date and can be loaded from the cache. This can significantly reduce the amount of time it takes for a web page or application to load, resulting in a more responsive and faster experience for the user.

Moreover, there are several other use cases for the 304 status code, besides caching web pages and images. It can be used for caching CSS and JavaScript files, as well as API responses. In the case of API responses, a 304 status code can be sent when a client has already fetched a resource and doesn't need an updated version of that data. Again, this reduces server load, bandwidth usage, and improves the overall performance of the application.

To send a 304 Not Modified status code, the server typically checks the resource's modification date or version number to determine whether the requested resource has been modified since the last time it was accessed by the client. If the resource has not been modified, the server sends a 304 status code along with the appropriate headers. These headers indicate to the client that it can safely use the cached version of the resource, rather than requesting a new version from the server.

In the case of an image, for example, the server can send an E-Tag header, which is a unique identifier that represents the contents of the resource. The client can then send this E-Tag value back to the server on subsequent requests, allowing the server to quickly determine whether a new version of the image needs to be sent or if the cached version is up to date.

To summarize, the 304 status code is a powerful tool for optimizing web applications and improving the user experience. By caching frequently accessed resources and using 304 status codes to avoid unnecessary requests, we can improve the performance and speed of our web applications. Additionally, there are several other use cases for the 304 status code, beyond caching web pages and images, including API responses and CSS and JavaScript files.

Popular questions

Sure, I’d be happy to provide you with five questions and answers related to the topic of status code 304 with code examples:

  1. What is the purpose of the 304 status code?
    Answer: The 304 status code, "Not Modified," reduces the number of requests and server workload required to serve the same content repeatedly. Instead of returning the full resource, the server sends a 304 status code and a few headers indicating that the client can use the cached version of the resource.

  2. When is the 304 status code useful in web applications?
    Answer: The 304 status code is useful in web applications when the same web page or resource is requested by multiple users repeatedly. This case helps to reduce bandwidth consumption and improve application performance.

  3. How does a server handle a request for a resource that has not been modified with the 304 status code?
    Answer: If a server receives a request for a resource that has not been modified, it sends a 304 status code along with the necessary headers, indicating that the client can use the cached version of the resource.

  4. What are some of the use cases for the 304 status code beyond caching web pages and images?
    Answer: The 304 status code can also be used for caching CSS and JavaScript files, as well as API responses. In the case of API responses, a 304 status code can be sent when a client has already fetched a resource and doesn't need an updated version of that data.

  5. Can you provide an example of how to send a 304 status code using PHP?
    Answer: Sure, here's an example:

$lastModified = new DateTime("2021-08-08T00:00:00Z");
$currentDateTime = new DateTime();
if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) && strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]) >= $lastModified->getTimestamp()) {
  header("HTTP/1.1 304 Not Modified");
  exit();
} else {
  header("Last-Modified: " . $lastModified->format(DateTime::RFC2822));
  echo "<h1>Welcome to my website</h1><img src='/image.jpg'>" . $currentDateTime->format(DateTime::RFC2822);
}

In this example, we set the Last-Modified header to the date on which the resource was last modified. Then, we check if the HTTP_IF_MODIFIED_SINCE header is present in the request headers, and its value is equal to or greater than the Last-Modified header. If this condition is true, we send a 304 status code without any body content. Otherwise, we return a response with the Last-Modified header and the current time.

Tag

"304-Not Modified"

I am a driven and diligent DevOps Engineer with demonstrated proficiency in automation and deployment tools, including Jenkins, Docker, Kubernetes, and Ansible. With over 2 years of experience in DevOps and Platform engineering, I specialize in Cloud computing and building infrastructures for Big-Data/Data-Analytics solutions and Cloud Migrations. I am eager to utilize my technical expertise and interpersonal skills in a demanding role and work environment. Additionally, I firmly believe that knowledge is an endless pursuit.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top