Swr: [Idea] Authentication example

Created on 31 Mar 2020  路  14Comments  路  Source: vercel/swr

Hello!

After a few people have already mentioned over at the Next.js repo that Zeit uses SWR for handling authentication on for example the /dashboard page of zeit.co I think a simple example would interest a lot of people, myself included.

This I think would need a bigger scale example, like a whole Next.js starter with some /api endpoints (skipping on the actual implementation and just returning a placeholder cookie etc.).

example

Most helpful comment

For sure @vassbence 馃憤 I've been working on a realworld example for a while. It covers a lot of use cases including authentication just like you said. Stay tuned!

All 14 comments

For sure @vassbence 馃憤 I've been working on a realworld example for a while. It covers a lot of use cases including authentication just like you said. Stay tuned!

Looking forward to more examples. Also more graphql related things as it quickly gets messy if you don't use REST.

For bearer authentication I use the following:

<SWRConfig
    value={{
        fetcher: async (url) => {
            const res = await fetch(url, {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${state.tokens?.access}`,
                },
            });
            return res.json();
        },
    }}
>
    {children}
</SWRConfig>

@darbio Error handling? Login Redirect? Redirect to the current page after refresh? refetch? ...

Hope they made the example!

For sure @vassbence 馃憤 I've been working on a realworld example for a while. It covers a lot of use cases including authentication just like you said. Stay tuned!

any news? :)

@darbio Error handling? Login Redirect? Redirect to the current page after refresh? refetch? ...

These are handled outside of the fetcher because the responsibility of the fetcher is to fetch, and not handle authentication.

@darbio so what do you do when you fetch and you get a 401?

I throw an error and catch it with an Error Boundary and redirect there

@darbio Error handling? Login Redirect? Redirect to the current page after refresh? refetch? ...

https://github.com/vercel/next.js/blob/canary/examples/with-iron-session/lib/useUser.js

This is a good example made for next.js, it is even using SWR

@darbio so what do you do when you fetch and you get a 401?

I don't - the refreshing of tokens and logging in etc. is managed by my Authentication service (which, irrelevantly, is Cognito via Amplify). If the user gets to a point where they are getting a 401 they are doing "somethingDodgy" ^TM.

If I needed to handle 401's I would throw an NotAuthorizedError and handle at the application error boundary to perform a refresh and redirect to the page as @sergiodxa suggested. Something along the lines of:

<SWRConfig
    value={{
        fetcher: async (url) => {
            const res = await fetch(url, {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${state.tokens?.access}`,
                },
            });
            if (!res.ok()) {
                if (res.statusCode === 401) throw new NotAuthorizedError(res.statusMessage);
                else throw new Error(res.statusMessage);
            }
            return res.json();
        },
    }}
>
    {children}
</SWRConfig>

I like the sample provided by @vassbence and I might experiment with that. My original statement of it not being the responsibility of the fetcher to handle this, remains my opinion. And you know what they say about opinions :)

My example is not meant to cover all bases, but it does show how I use it in a (relatively simple) example. YMMV.

Hey there, I was planning to jump in here but @vassbence beat me to it: if you're looking for a Next.js authentication system using SWR that is similar to the one from https://vercel.com/dashboard then https://github.com/vvo/next-iron-session could be one way to do it. Everything is detailed in the README and if you're having trouble with the package just open issues on the project, thanks!

For sure @vassbence 馃憤 I've been working on a realworld example for a while. It covers a lot of use cases including authentication just like you said. Stay tuned!

Would love to see this. 馃檪

For sure @vassbence 馃憤 I've been working on a realworld example for a while. It covers a lot of use cases including authentication just like you said. Stay tuned!

Would love to see this. 馃檪

https://swr.vercel.app/examples/auth

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sergiodxa picture sergiodxa  路  4Comments

dandrei picture dandrei  路  3Comments

needcaffeine picture needcaffeine  路  3Comments

bbenezech picture bbenezech  路  5Comments

timurmaio picture timurmaio  路  3Comments