logoalt Hacker News

yellow_leadlast Thursday at 7:12 PM2 repliesview on HN

I had a site where the user can upload a file < 5MB. There may be a way to check this on the frontend, but for security reasons, it has to be checked on the backend too.

If it exceeds it, I returned 400. I had to add an event listener to check for the code (htmx:afterRequest) and show an alert(), but this gets difficult to manage if there's multiple requests to different endpoints on the page. Looking at it now, maybe I should have configured HTMX to swap for 4xx.


Replies

MrPowerGamerBRlast Thursday at 9:53 PM

I have something similar on my website, and my solution was to make server driven modal/toast responses.

Allow the server to return a modal/toast in the response and, in your frontend, create a "global" listener that listens to `htmx:afterRequest` and check if the response contains a modal/toast. If it does, show the modal/toast. (or, if you want to keep it simple, show the content in an alert just like you already do)

This way you create a generic solution that you can also reuse for other endpoints too, instead of requiring to create a custom event listener on the client for each endpoint that may require special handling.

If you are on htmx's Discord server, I talked more about it on this message: https://discord.com/channels/725789699527933952/909436816388...

At the time I used headers to indicate if the body should be processed as a trigger, due to nginx header size limits and header compression limitations. Nowadays what I would do is serialize the toast/modal as a JSON inside the HTML response itself then, on `htmx:afterRequest`, parse any modals/toasts on the response and display them to the user.

show 1 reply