Home > Net >  Next Auth always returns ok: false and status: 302 for sign in. Even with redirect = false
Next Auth always returns ok: false and status: 302 for sign in. Even with redirect = false

Time:12-13

I'm using Next Auth with credentials to sign in, that's the below react sign in function.

    signIn('credentials', {
        redirect: false,
        email: email,
        password: password,
        remember: remember,
    })
        .then(res => {
            // Should never be undef, probs gonna screw me over in the future
            return res!;
        })
        .catch(err => {
            throw err;
        })

With my [...nextauth].ts looking like below, very default settings. For test, I set my authorise to always return true. Which, means the frontend should return { ok: true }. However it always returns { ok: false, status: 302 }

export default NextAuth({
    // https://next-auth.js.org/configuration/providers
    providers: [
        CredentialsProvider({
            // The name to display on the sign in form (e.g. 'Sign in with...')
            name: 'Credentials',
            // The credentials is used to generate a suitable form on the sign in page.
            // You can specify whatever fields you are expecting to be submitted.
            // e.g. domain, username, password, 2FA token, etc.
            // You can pass any HTML attribute to the <input> tag through the object.
            credentials: {
                email: {
                    label: 'Email',
                    type: 'text',
                    placeholder: 'jsmith',
                },
                password: { label: 'Password', type: 'password' },
                remember: {
                    label: 'Remember',
                    type: 'boolean'
                }
            },
            async authorize(credentials) {
                return true;
            },
        }),
    ],
    // Database optional. MySQL, Maria DB, Postgres and MongoDB are supported.
    // https://next-auth.js.org/configuration/databases
    //
    // Notes:
    // * You must install an appropriate node_module for your database
    // * The Email provider requires a database (OAuth providers do not)
    // database: process.env.DATABASE_URL,

    // The secret should be set to a reasonably long random string.
    // It is used to sign cookies and to sign and encrypt JSON Web Tokens, unless
    // a separate secret is defined explicitly for encrypting the JWT.
    secret: process.env.NEXTAUTH_SECRET,

    session: {
        // Use JSON Web Tokens for session instead of database sessions.
        // This option can be used with or without a database for users/accounts.
        // Note: `strategy` should be set to 'jwt' if no database is used.
        strategy: 'jwt',

        // TODO: Enable max age after testing complete
        // Seconds - How long until an idle session expires and is no longer valid.
        // maxAge: 30 * 24 * 60 * 60, // 30 days

        // Seconds - Throttle how frequently to write to database to extend a session.
        // Use it to limit write operations. Set to 0 to always update the database.
        // Note: This option is ignored if using JSON Web Tokens
        // updateAge: 24 * 60 * 60, // 24 hours
    },

    // JSON Web tokens are only used for sessions if the `strategy: 'jwt'` session
    // option is set - or by default if no database is specified.
    // https://next-auth.js.org/configuration/options#jwt
    jwt: {
        // A secret to use for key generation (you should set this explicitly)
        secret: process.env.NEXTAUTH_SECRET,
        // Set to true to use encryption (default: false)
        // encryption: true,
        // You can define your own encode/decode functions for signing and encryption
        // if you want to override the default behaviour.
        // encode: async ({ secret, token, maxAge }) => {},
        // decode: async ({ secret, token, maxAge }) => {},
    },

    // You can define custom pages to override the built-in ones. These will be regular Next.js pages
    // so ensure that they are placed outside of the '/api' folder, e.g. signIn: '/auth/mycustom-signin'
    // The routes shown here are the default URLs that will be used when a custom
    // pages is not specified for that route.
    // https://next-auth.js.org/configuration/pages
    pages: {
        signIn: '/login', // Displays signin buttons
        // signOut: '/auth/signout', // Displays form with sign out button
        // error: '/auth/error', // Error code passed in query string as ?error=
        // verifyRequest: '/auth/verify-request', // Used for check email page
        // newUser: '/register' // If set, new users will be directed here on first sign in
    },

    // Callbacks are asynchronous functions you can use to control what happens
    // when an action is performed.
    // https://next-auth.js.org/configuration/callbacks
    callbacks: {
        // async signIn({ user, account, profile, email, credentials }) { return true },
        // async redirect({ url, baseUrl }) { return baseUrl },
        async session({ session, token, user }) {
            // Add in serverside set user and errors into session to access cilentside
            session.user = token.user
            session.error = token.error

            return session;
         },
        async jwt({ token, user, account, profile, isNewUser }) {
            if (!user) return token;

            // User exists, set into jwt token to set into session
            // Required to auth requests later in client side
            return {
                token: token,
                user: user
            };
        }
    },

    // Events are useful for logging
    // https://next-auth.js.org/configuration/events
    events: {
        async signOut({ token, session }) {
            // Delete token and sessions
            token = {};
            session = {};
        }
    },

    // TODO: Disable debug msg
    // Enable debug messages in the console if you are having problems
    debug: true,
    }
);

Is this something others have encountered?

Versions

"next": "^13.0.3",
"next-auth": "^4.18.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",

CodePudding user response:

I just updated to 4.18.4 and fix my login problem. Try to update dependency

CodePudding user response:

This is a bug in next-auth and fix was already applied on version ^4.18.5.

  • Related