Next.js Discord

Discord Forum

Fetching django to check authentication in nextjs middleware

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
I am using a django rest api backend to handle authentication for my nextjs frontend. I was wondering how I can fetch from my backend in the nextjs middleware to handle authentication and do stuff like manage protected routes.

58 Replies

in nextjs middleware, do the same thing you do in django
like a verify session
api route
I'm not sure if this is the best solution
@"use php" in nextjs middleware, do the same thing you do in django
Masai LionOP
im trying to fetch my django backedn but im getting fetch errors
Can you share screenshot of the error?
@"use php" Can you share screenshot of the error?
Masai LionOP
Error: fetch failed
2024-08-02T22:55:51.901284293Z     at context.fetch 
...
2024-08-02T22:55:51.901308793Z     errno: -111,
2024-08-02T22:55:51.901310293Z     code: 'ECONNREFUSED',
2024-08-02T22:55:51.901311793Z     syscall: 'connect',
2024-08-02T22:55:51.901313293Z     address: '127.0.0.1',
2024-08-02T22:55:51.901314627Z     port: 443
2024-08-02T22:55:51.901316168Z   }
2024-08-02T22:55:51.901318002Z }
@"use php" Are you using edge runtime?
Masai LionOP
Idk what that is
@Masai Lion Error: fetch failed 2024-08-02T22:55:51.901284293Z at context.fetch ... 2024-08-02T22:55:51.901308793Z errno: -111, 2024-08-02T22:55:51.901310293Z code: 'ECONNREFUSED', 2024-08-02T22:55:51.901311793Z syscall: 'connect', 2024-08-02T22:55:51.901313293Z address: '127.0.0.1', 2024-08-02T22:55:51.901314627Z port: 443 2024-08-02T22:55:51.901316168Z } 2024-08-02T22:55:51.901318002Z }
Sun bear
How do you run django locally?

Did you use localhost:8000 or 127.0.0.1:8000 as base path?

Maybe share the part of the code where you fetch django.

And in django did you disable csrf protection for the route?

Just debugging braunstorming
@Sun bear How do you run django locally? Did you use localhost:8000 or 127.0.0.1:8000 as base path? Maybe share the part of the code where you fetch django. And in django did you disable csrf protection for the route? Just debugging braunstorming
Masai LionOP
import { NextRequest, NextResponse } from "next/server";

export async function middleware(request) {
    const test = fetch("https://localhost/api/_allauth/browser/v1/config")

    return NextResponse.next()
}
@Masai Lion js import { NextRequest, NextResponse } from "next/server"; export async function middleware(request) { const test = fetch("https://localhost/api/_allauth/browser/v1/config") return NextResponse.next() }
Sun bear
Thanks. I run django via docker there it is localhost:8000

You could check that. And is it really https?

Did you paste the url in the browser and check if it logs in django?
that url works on client components
but not server ones
@Masai Lion yeah im using a local ssl
Sun bear
Btw you should await the fetch in general. Not sure if its part if the problem.

So client side the same fetch request us working?
@Sun bear Btw you should `await` the fetch in general. Not sure if its part if the problem. So client side the same fetch request us working?
Masai LionOP
oh yeah i did that in a previous attempt but stil lsame problem
client side fetch works
starts breaking on server components
including middleware
same errors for both
Sun bear
Does your django route require any cookies/credentials that are set client side automatically?
Masai LionOP
no
this one is just a get request to get some info from the server
wait actually
i think it does use credentials
Sun bear
If you want you can share the django view as well
Masai LionOP
import { NextRequest, NextResponse } from "next/server";

export async function middleware(request) {
    const test = await fetch(`https://localhost/api/_allauth/browser/v1/config`, {
        method: "GET",
        mode: "cors",
        credentials: "include",
        headers: {
            "Content-Type": "application/json",
        },
    });
    return NextResponse.next();
}

src/middleware.js (4:23) @ fetch
2024-08-03T23:08:59.300936636Z  ⨯ fetch failed
2024-08-03T23:08:59.300946594Z   2 |
2024-08-03T23:08:59.300949177Z   3 | export async function middleware(request) {
2024-08-03T23:08:59.300975719Z > 4 |     const test = await fetch(`https://localhost/api/_allauth/browser/v1/config`, {
2024-08-03T23:08:59.300994052Z     |                       ^
2024-08-03T23:08:59.301006802Z   5 |         method: "GET",
2024-08-03T23:08:59.301009177Z   6 |         mode: "cors",
2024-08-03T23:08:59.301011177Z   7 |         credentials: "include",
@Sun bear If you want you can share the django view as well
Masai LionOP
im using a package that handles the view
this is the specific command tho
Sun bear
Ok got it.

My guess is it is because of missing credentials in the request. Thats why it works clientside.

You cant include credentials like that serverside. You can check here:

https://stackoverflow.com/questions/77133684/how-to-send-cookies-with-fetch-api-in-next-js-13-4-middleware-for-authorization
Most likely you have to pass the token like manually. First you could check the browser console to see how the auth token is called
the thing im doing is kinda weird
the api im calling doesnt actually take in any cookies or credentials
but it sets some cookies that need to be set
which requires included credentials
let me try with one that requires credentials tho
@Masai Lion the api im calling doesnt actually take in any cookies or credentials
Sun bear
True. Based on the docs you dont need to provide a token. Strange
@Sun bear True. Based on the docs you dont need to provide a token. Strange
Masai LionOP
i think you just need to include credentials whe nyou wanna set a cookie
@Sun bear True. Based on the docs you dont need to provide a token. Strange
Masai LionOP
i took out credentials included and im still getting fetch errors before it hits the server
Sun bear
When you paste this in your browser:

https://localhost/api/_allauth/browser/v1/config

What does the django log say?
Sun bear
And what does this log?

import { NextRequest, NextResponse } from "next/server";

export async function middleware(request) {
    const test = await fetch(`https://localhost/api/_allauth/browser/v1/config`, {
        method: "GET",
        mode: "cors",
        headers: {
            "Content-Type": "application/json",
        },
    });
console.log(test.status)
const data = await test.json()
console.log(data)
    return NextResponse.next();
}
Masai LionOP
src/middleware.js (4:23) @ fetch
2024-08-03T23:25:32.916915971Z  ⨯ fetch failed
2024-08-03T23:25:32.916917929Z   2 |
2024-08-03T23:25:32.916919929Z   3 | export async function middleware(request) {
2024-08-03T23:25:32.916922096Z > 4 |     const test = await fetch(`https://localhost/api/_allauth/browser/v1/config`, {
2024-08-03T23:25:32.916924387Z     |                       ^
2024-08-03T23:25:32.916926221Z   5 |         method: "GET",
2024-08-03T23:25:32.916928429Z   6 |         mode: "cors",
2024-08-03T23:25:32.916930262Z   7 |         credentials: "include",
fetch fails before logs
Sun bear
Last idea from my side:

import { NextRequest, NextResponse } from "next/server";

export async function middleware(request) {
    const test = await fetch("https://localhost/api/_allauth/browser/v1/config");
console.log(test.status)
const data = await test.json()
console.log(data)
    return NextResponse.next();
}
Masai LionOP
same error
 src/middleware.js (4:23) @ fetch
2024-08-03T23:32:07.204850208Z  ⨯ fetch failed
2024-08-03T23:32:07.204853000Z   2 |
2024-08-03T23:32:07.204855500Z   3 | export async function middleware(request) {
2024-08-03T23:32:07.204857917Z > 4 |     const test = await fetch(`https://localhost/api/_allauth/browser/v1/config`);
2024-08-03T23:32:07.204860417Z     |                       ^
2024-08-03T23:32:07.204862458Z   5 |     console.log(test.status)
2024-08-03T23:32:07.204864458Z   6 |     const data = await test.json()
2024-08-03T23:32:07.204866625Z   7 |     console.log(data)
idk why the fetch itself is failing
its not even hitting the server before it fails
Sun bear
Okay. Sorry 😅 if it wont work in browser directly or clientside maybe there could you be a bug.

But like that i dont have any further ideas. Please tag me when you solved it
Masai LionOP
ok thanks
Sun bear
I had to ask Chat gpt:

Possible Issues and Fixes:Localhost on the Server-Side: When running server-side code, localhost refers to the server environment, not your local machine. Try using the actual server address or 127.0.0.1.Self-Signed SSL Certificates: If you are using HTTPS with a self-signed certificate, the server-side fetch might reject it. You can either switch to HTTP (only for local development) or handle SSL properly