I started using the django dj-rest-auth package with react and i ran across the following issue:
When i logout it will clear the key inside the local storage but not inside the Django backend.
When i go to the API endpoint page and click the "send post request" button it will do it, but it won't do it when i use my frontend to logout.
This is the code i'm using to accomplish this:
navbar.js
import { useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios"
import { AuthContext } from "../contexts/AuthContext";
import { API } from "../api"
export function Navbar() {
const { user, logout } = useContext(AuthContext)
const navigate = useNavigate()
function handleSubmit() {
axios.post(API.auth.logout)
.then(res => {
logout()
navigate('/login')
})
}
api.js
const baseURL = "http://127.0.0.1:8000"
const apiURL = `${baseURL}/api`
export const API = {
auth: {
login: `${baseURL}/dj-rest-auth/login/`,
logout: `${baseURL}/dj-rest-auth/logout/`,
passwordReset: `${baseURL}/dj-rest-auth/password/reset/`,
passwordResetConfirm: `${baseURL}/dj-rest-auth/password/reset/confirm/`,
signup: `${baseURL}/dj-rest-auth/registration/`,
verifyEmail: `${baseURL}/dj-rest-auth/registration/verify-email/`
}
}
app.js
import React, { useContext } from "react";
import {
BrowserRouter as Router,
Routes,
Route,
Navigate
} from "react-router-dom";
import { AuthContext, AuthContextProvider } from './contexts/AuthContext'
import { Login } from './components/Login'
import { Reset } from './components/Reset'
import { Navbar } from "./components/Navbar";
import { Signup } from "./components/Signup"
import { ConfirmEmail } from "./components/ConfirmEmail";
import { ResetConfirm } from './components/ResetConfirm'
function PrivateRoute({ children }) {
const { user } = useContext(AuthContext)
return user ? children : <Navigate replace to="/login" />
}
export default function App() {
return (
<Router>
<AuthContextProvider>
<div>
<Navbar />
{/* A <Routes> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<div className="max-w-4xl mx-auto py-5 px-4">
<Routes>
<Route path="/settings" element={<PrivateRoute><Settings /></PrivateRoute>} exact />
<Route path="/login" element={<Login />} exact />
<Route path="/signup" element={<Signup />} exact />
<Route path="/reset" element={<Reset />} exact />
<Route path="/password-reset/confirm/:uid/:token" element={<ResetConfirm />} exact />
<Route path="/accounts/confirm-email/:key" element={<ConfirmEmail />} exact />
</Routes>
</div>
</div>
</AuthContextProvider>
</Router>
);
}
Apparently this is not possible so i started using JWT Tokens instead which are part of dj-rest-auth aswell:
REST_USE_JWT = True
More details on the JWT configuration can be found here: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/index.html