Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can you provide cookies/auth to code running on the server? #8017

Closed
rtman opened this issue Jul 11, 2023 · 3 comments
Closed

How can you provide cookies/auth to code running on the server? #8017

rtman opened this issue Jul 11, 2023 · 3 comments
Labels
question Ask how to do something or how something works

Comments

@rtman
Copy link

rtman commented Jul 11, 2023

Question 💬

In my nextjs app I call pages/api routes from getServerSideProps in order to prepopulate data from the database. I also call these apis from the client after ssr to check for updated data. We have placed all database read/write calls behind apis for security reasons and to avoid exposing secrets.

I notice that on the first load of the app, getServerSession is null and the resulting apis that I'm calling return 401 because I have them secured for authentication. I've looked over the docs and the issues here, but haven't found a solid path forward. From looking at #7423 (comment) I found the reason is that cookies are not available server side and the suggestion is to query the db directly (without an api) or use the nextjs headers function.

The first would require a large refactor to run the db queries directly in SSR but use the api for pure clientside, also creating duplicates of what is essentially the same action. The second I find confusing because the headers() function requires configuration in next.config.js if I'm not mistaken. How would you statically configure these headers to work with next-auth?

What is the recommended way to get around this? Can I pass the relevant cookie/data manually? Can I provide an authorization header like the following:

        headers: {
          Authorization: `Bearer ${data?.accessToken}`
        }

For reference I'm using the supabase adapter.

How to reproduce ☕️

N/A

Contributing 🙌🏽

Yes, I am willing to help answer this question in a PR

@rtman rtman added the question Ask how to do something or how something works label Jul 11, 2023
@Dragate
Copy link
Contributor

Dragate commented Jul 12, 2023

  • The comment you linked was referring to the headers function of the app router, nothing to do with next.config.js.
  • Making calls to your API from your server degrades performance as you have unnecessary roundtrips.
  • When using getServerSideProps in the the pages router you already have the request headers at your disposal:
import type { GetServerSidePropsContext } from "next"
import type { IncomingHttpHeaders } from "http"

async function nextFetch<T = unknown>(url: string, headers: IncomingHttpHeaders = {}): Promise<T> {
    const params = {
        headers: {
            "Content-Type": "application/json",
            ...headers as HeadersInit,
        },
    }
    return fetch(`${process.env.SITE_URL}${url}`, params).then(r => r.json())
}

export async function getServerSideProps({ req }: GetServerSidePropsContext) {
    const invoices = await nextFetch("/api/invoices", req.headers)

    return {
        props: {
            invoices,
        },
    }
}

@rtman
Copy link
Author

rtman commented Jul 12, 2023

  • The comment you linked was referring to the headers function of the app router, nothing to do with next.config.js.

Ah I have not used app router yet and thought the comment was referring to https://nextjs.org/docs/pages/api-reference/next-config-js/headers. I'll take a look at the headers function in app router then.

  • Making calls to your API in from your server degrades performance as you have unnecessary roundtrips.

Thats fair, tho it does solve security issues and doesn't require doing the same thing two different ways on the server and client.

  • When using getServerSideProps in the the pages router you already have the request headers at your disposal:

True I will give this a try, thanks.

@rtman
Copy link
Author

rtman commented Jul 12, 2023

Works, thanks!

@rtman rtman closed this as completed Jul 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests

2 participants