Next.js is a robust React framework that provides an excellent developer experience for building server-side rendered and statically generated web applications. By default, Next.js serves static files from the public directory bundled during build time. However, this approach only works for static r that must be served at runtime.
The Solution
To serve these dynamically uploaded files, we can create a custom API route that reads the files from our chosen directory and serves them on demand. This approach gives us more control over how the files are served and allows us to implement additional features like image resizing and format conversion.
Let's dive into the code that makes this possible:
Let's break down this code and understand how it works:
- We import necessary modules, including
pathandfsfor file system operations,NextRequestandNextResponsefrom Next.js,fileTypeFromBufferto determine file types, andsharpfor image processing. - The
GETfunction handles incoming requests to our API route. - We extract query parameters from the request URL, including the resource name and optional width, height, and quality parameters for image resizing.
- We construct the file path using
process.cwd()and an optionalRESOURCE_PATHenvironment variable. - If the file exists, we read it into a buffer and determine its content type.
- For image files, we use the
sharplibrary to resize the image if width and height parameters are provided. We convert the image to WebP format for better performance. - We serve the file buffer with the appropriate content type for non-image files.
- If the file doesn't exist, we return a 404 status code.
- Any errors during this process are caught and result in a 500 status code.
Using the API
To use this API, you would typically make a GET request to the endpoint where this route is set up, including the necessary query parameters. For example:
/api/resource?resource=example.jpg&w=800&h=600&q=80
This would serve the file "example.jpg" from your resources directory, resizing it to 800x600 pixels with 80% quality if it's an image.
Conclusion
By implementing this custom API route, you can serve dynamically uploaded files in your Next.js application from any directory you choose. This approach gives you fine-grained control over how files are served and allows for on-the-fly image processing.
Remember to secure this endpoint appropriately and consider implementing caching mechanisms for better performance in a production environment.
Building something bigger than a code snippet? ARITS does product engineering, architecture first.
.avif)




