question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Add a function to fetch auth user from cookies on the server side

See original GitHub issue

Is your feature request related to a problem? Please describe. I am trying to authenticate requests that come into my Next.js API routes, however, I am not able to pass the token from the useAuthUser hook into the Authorization header. This means that I cannot easily tell if a request is authenticated for my API routes.

Describe the solution you’d like and how you’d implement it It would make it very easy to achieve this if there was a function to get the AuthUser from the backend by passing in the req object. This would behave similarly to the setAuthCookies function that currently exists.

Alternatively (or additionally), I think it would be a great addition to have function wrappers that one can wrap their API Route handlers in, similar to withAuthUserTokenSSR but specifically focused for server-side API Routes.

Is this a breaking change? No, this would not be a breaking change.

Describe alternatives you’ve considered As far as I can tell, the only alternatives are to write custom logic to read and parse the cookies myself. This seems like a very brittle solution since it will break if the structure of the cookies used by this library will break.

Additionally, I have tried to use the method shown in examples of setting the Authorization header, however, for my use case this is not a viable option.

As far as I can tell, I do not think that this change would require significant changes from this library. I think exposing two functions (possible called getAuthUserFromCookies and withAuthUserTokenAPI or something similar), would solve my use case and greatly expand the functionality and flexibility of this library.

I have really enjoyed porting my own Firebase authentication scheme to this library, however, this is a significant challenge now for me. I’m happy to answer any further questions or possibly contribute as well.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:14
  • Comments:13 (7 by maintainers)

github_iconTop GitHub Comments

11reactions
zaverdencommented, Dec 30, 2021

for those how want to rely on cookie and not send token in headers there is a simple helper:

import { withAuthUserTokenSSR } from 'next-firebase-auth'

const checkServerSideAuth = typeof window !== 'undefined'
  ? null // "withAuthUserTokenSSR" can only be called server-side.
  : withAuthUserTokenSSR({
      whenAuthed: AuthAction.RENDER,
      whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,
      authPageURL: '401',
    })(({ AuthUser }) => ({ AuthUser, props: {} }))

export function withAuthUserTokenAPI(handler) {
  return async (req, res) => {
    const { AuthUser, redirect } = await checkServerSideAuth({ req, res })
    if (redirect) {
      res.status(401).json({ ok: false, code: 'unauthorized' })
      return
    }
    return handler(req, res, AuthUser)
  }
}

and then you wrap your API handler:

export default withAuthUserTokenAPI((req, res, user) => {
  // your code here
})
2reactions
zaverdencommented, Jan 7, 2022

@Rykuno for the first error just add async for a callback

-     })(({ AuthUser }) => ({ AuthUser, props: {} }))
+     })(async ({ AuthUser }) => ({ AuthUser, props: {} }))

for the second one - next-firebase-auth has wrong TS typings for withAuthUserTokenSSR (at least for 1.0.0-canary.5 and earlier), that’s why there is an error. I suggest to ignore it until typings are fixed. Use @ts-expect-error here

+    // @ts-expect-error wrong typings in lib. remove expect-error if typings are correct now
     const { AuthUser, redirect } = await checkServerSideAuth({ req, res });

Here is typed version: https://gist.github.com/zaverden/9f6579f262ac25b591dd814047e19b30

Read more comments on GitHub >

github_iconTop Results From Across the Web

Fetch API with Cookie - Stack Overflow
I called POST /api/auth and see that cookies were successfully received. Then calling GET /api/users/ with credentials: 'include' and got 401 unauth, ...
Read more >
Authenticating things with cookies on Next.js
Whenever we want to identify the user behind a network request, we check the cookies of said request, take our JWT token, and...
Read more >
Manage Session Cookies | Firebase Authentication
When a user signs out from the client side, handle it on the server side via an endpoint. A POST/GET request should result...
Read more >
Firebase: Introducing session cookies for server-side web apps
One way to achieve this is by getting hold of the ID token issued by Firebase Auth at sign-in, and then pass it...
Read more >
Authentication in Svelte using cookies - LogRocket Blog
You could add authorization functionality by adding something like a permissions array to the user object returned from getSession . You could ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found