Process the selection in the backend but let the client see the redirect

I have a url No, /users/sign_out

, which should bring the user from the system and redirect it to my root the URL, /

. I want to process this fetch through my service worker because I want to clear some items from the cache before sending back to root to the user. However, since the client doesn't see the redirect that happens when fetching from the worker, the user hits my splash screen, but sees the address before the redirect /users/sign_out

.

Is there a way currently that I can handle the fetch and also let the client see the correct final URL?

It looks like there will eventually be a method Response.redirect()

that will allow the response to be updated with the final url. It looks like there will probably also be some option finalURL

that will address this case as well. But is there anything I can use now? On Twitter, Jake Archibald (@jaffathecake) said that I can create a new Response myself, and I can, but even after doing some research on the spec and MDN docs, I still can't figure out how to specify the correct URL for it.

If there is actually a way to create a Response object that does what I want, can someone show me how it works?

+3


source to share


1 answer


Here's an example https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/mock-responses showing how you can create an object Response

and use it to respond to an event fetch

.

In this case, we create a response 200 OK

with a body, but there is nothing stopping you from creating an arbitrary response. You will probably need it 302 Found

for your use case, so you would do something like:



var responseInit = {
  status: 302,
  statusText: 'Found',
  headers: {
    Location: '/' // Or whatever URL you want to redirect to.
  }
};

var redirectResponse = new Response('', responseInit);
event.respondWith(redirectResponse);

      

You can include code that clears your caches inside a handler fetch

before responding to this event, and you obviously want to check the value first event.request.url

to make sure you only respond to requests for /users/sign_out

with your custom response.

+2


source







All Articles