Search code examples
javascriptnext.jsnext-auth

How to put a const in the main scope who depends of a function parameter?


I'm working with next-auth and I want to use unstable_getserversession. The doc say I must import options from an another file

import { authOptions } from 'pages/api/auth/[...nextauth]'

I can't achieve this :/

The file is here

Check the comments for understanding my problem. I need to put this providers const in the main scope to export the options

What is the way to do this ?

export default async function auth(req: any, res: any) {
  const providers = [             // I don't know how to get this const outside of the auth()
    CredentialsProvider({         // scope, because it contain...
      name: "Ethereum",
      credentials: {
        message: {
          label: "Message",
          type: "text",
          placeholder: "0x0",
        },
        signature: {
          label: "Signature",
          type: "text",
          placeholder: "0x0",
        },
      },
      async authorize(credentials) {        // this function ...
        try {
          const siwe = new SiweMessage(JSON.parse(credentials?.message || "{}"))
          const nextAuthUrl = new URL(process.env.NEXTAUTH_URL)

          const result = await siwe.verify({
            signature: credentials?.signature || "",
            domain: nextAuthUrl.host,
            nonce: await getCsrfToken({ req }),   // doing this call, with the "req"
          })                                      // parameter, given by auth()
                                                  // at the first line :/

Solution

  • Do like this:

    let providers; <-----------
    
    export default async function auth(req: any, res: any) {
      providers = [             // I don't know how to get this const outside of the auth()
        CredentialsProvider({         // scope, because it contain...
          name: "Ethereum",
          credentials: {
            message: {
              label: "Message",
              type: "text",
              placeholder: "0x0",
            },
            signature: {
              label: "Signature",
              type: "text",
              placeholder: "0x0",
            },
          },
          async authorize(credentials) {        // this function ...
            try {
              const siwe = new SiweMessage(JSON.parse(credentials?.message || "{}"))
              const nextAuthUrl = new URL(process.env.NEXTAUTH_URL)
    
              const result = await siwe.verify({
                signature: credentials?.signature || "",
                domain: nextAuthUrl.host,
                nonce: await getCsrfToken({ req }),   // doing this call, with the "req"
              })                                      // parameter, given by auth()
                                                      // at the first line :/