fix: cannot set headers after they are sent to the client #875
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
π Linked issue
β Type of change
π Description
This PR fixes a long-lasting bug. On first redirect from a protected pages to the login page using the
authjsprovider, you would often get the following message in the console:This issue originates from the problem of how do we set a redirect inside the SSR context if the page is protected. Until now we used a outdated workaround from Nuxt. I did some digging and managed to find a better solution here.
The difference
In the old version we did the following:
import.meta.servernuxtApp.ssrContextandnuxtApp.ssrContext.eventwere seth3redirect on the server-sideThe issue then occurred when the client-side redirect occurs different to the server-side redirect. At that point the client would already be redirected, but the
h3event would still try and set the headers. Resulting in the error.In the new version I remove the dependency on
h3completely and do the following:import.meta.servernuxtApp.ssrContextis set (will be set on SSR)metaredirectI set the following as the ssr-rendered response:
When using
curlto get the initially SSR-render content, we can also see that the responses are the same. So we are functionally doing the same thing as before, just cutting outh3and setting the content ourselves to avoid issues.Main
This PR
This solution works, maintains protection and ensures that the error does not occur anymore!
Verification
To test that this resolves the issue:
mainand started the production build and received the error after directly accessing a protected URL (in my case/protected/globally)Main:
Screen.Recording.2024-08-22.at.21.14.23.mov
This PR:
Screen.Recording.2024-08-22.at.21.13.21.mov
π Checklist