Search code examples
reactjsnext.jsauthkit

Unable To Store Cookie With react-auth-kit


I've been trying to create a React website that allows you to log in, but I've been having issues getting the react-auth-kit to work with my code. I've been able to successfully obtain a token and then use the signIn function, but it's not storing the cookie in the web browser.

Here is the code I'm using to log in:

console.log('Sending request to FastAPI server...');
const response = await fetch('http://192.168.1.21:8000/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ email, password }),
});

if (!response.ok) {
  throw new Error('Invalid credentials');
}

const data = await response.json();
console.log('Received response:', data);

const token = data?.token;
if (!token) {
  throw new Error('Token is undefined');
}

const signInParams = {
  auth: {
    token: token,
    type: 'Bearer',
  },
  refresh: data?.refreshToken, // Assuming your backend provides a refresh token
  userState: { email: email, name: email },
};

console.log('Signing in with params:', signInParams);

if (signIn(signInParams)) {
  console.log('Successfully signed in!');
  push('/dashboard');
} else {
  throw new Error('Failed to sign in');
}
} catch (err) {
  console.log('Error:', err.message);
  setError('Invalid credentials');
}

I've already wrapped my whole page with a provider. Below is the code for that.

import React from 'react';
import createStore from 'react-auth-kit/createStore';
import AuthProvider from 'react-auth-kit/AuthProvider';
import { UserData } from '@/types';

const store = createStore<UserData>({
  authName: '_auth',
  authType: 'cookie',
  cookieDomain: '192.168.1.21:3000',
  cookieSecure: false,
  debug: true,
});

const Providers = ({ children }: { children: React.ReactNode }) => {
  return (
    <AuthProvider store={store}>
      {children}
    </AuthProvider>
  );
};

export default Providers;

I then have a page that I would like to password protect with the import NextAuth from '@auth-kit/next'; imported and set up.

Any help would be greatly appreciated. I've tried removing and updating them and re-writing the code, but none of that makes it store the cookie, which then makes it think I'm not logged in. I am new to React, so I might be missing something simple.


Solution

  • Basically if the JWT token doesn't have an expiry then it will be removed as soon as it is saved as react auth kit assumes it's already expired.

    https://github.com/react-auth-kit/react-auth-kit/issues/1653

    https://github.com/react-auth-kit/react-auth-kit/issues/1653#issuecomment-2041654024