Why are my Django REST Framework and Angular app making duplicate backend requests?

I’m having a weird issue with my Django REST Framework (DRF) and Angular app. It seems to be making duplicate backend requests for no apparent reason.

Here’s what I’m seeing in my logs:

GET /api/lessons: 401 Unauthorized
POST /api/lesson-data: 401 Unauthorized
POST /api/token/refresh: 400 Bad Request
GET /api/lessons: 200 OK
POST /api/lesson-data: 200 OK
GET /api/user/verify: 200 OK

My HTTP interceptor in Angular confirms this:

Request sent to: http://localhost:8000/api/lessons
Request sent to: http://localhost:8000/api/lesson-data
Request sent to: http://localhost:8000/api/user/verify

I’m using simplejwt for authentication. My token refresh view looks something like this:

def post(self, request):
    refresh_token = request.COOKIES.get('refresh_token')
    if not refresh_token:
        raise ValidationError('Missing refresh token')
    serializer = TokenRefreshSerializer(data={'refresh': refresh_token})
    serializer.is_valid(raise_exception=True)
    return Response({'access': serializer.validated_data['access']})

And here’s a sample of one of my API views:

class LessonDataView(APIView):
    permission_classes = [IsAuthenticated]
    
    def post(self, request):
        lesson = LessonModel.objects.get(id=request.data.get('id'))
        if UserCourse.objects.filter(user=request.user, course=lesson.course).exists():
            if lesson.content_file:
                with open(lesson.content_file.path, 'rb') as file:
                    content = file.read().decode('utf-8')
                return Response({'content': content})
        return Response({'error': 'Unauthorized'}, status=401)

I’ve tried debugging by logging the refresh tokens, and it seems like the first request always has a None refresh token, while the second one (about a second later) has a valid token.

Any ideas on what might be causing these duplicate requests and how to fix it?

This issue likely stems from your token refresh mechanism. The first request fails due to an expired or missing access token, triggering a token refresh. However, the original request isn’t automatically retried after the refresh.

To resolve this, implement a retry mechanism in your Angular HTTP interceptor. When receiving a 401 response, refresh the token and then retry the original request with the new access token. This approach should eliminate the duplicate requests and improve your app’s efficiency.

Additionally, consider implementing token expiration checks on the client-side before making API calls. This proactive approach can reduce unnecessary 401 responses and improve overall performance. Remember to handle edge cases, such as simultaneous requests during token refresh, to ensure a smooth user experience.

yo, sounds frustrating! have u checked ur angular services? sometimes they can fire off multiple requests if not set up right. also, maybe try console.logging in ur interceptor to see exactly when those requests are happening. could be a race condition or smthing. good luck figuring it out!

hmm, interesting issue! have u considered checking ur angular interceptor? maybe it’s triggering multiple requests accidentally? also, whats ur token refresh strategy? sometimes setting a buffer time before expiration can help avoid those pesky 401s. curious to hear more about ur setup - what kinda data are u fetching from the api?