I'm developing a To-Do app with authentication, using Next.js 12, Mongoose and JWT.
The user logs in and gets a cookie called userAuthToken
which has: username, password and user id.
When an authenticated user creates a new task, a POST
request ( with the task's data ) is sent to src/pages/api/tasks/index.js
, where the authentication is checked and the new task is assigned to the user's document in MongoDB ( this part is not working yet ).
In src/pages/api/tasks/index.js
( where tasks are sent from client ), i am trying to access cookies in order to check authentication like so:
export default async function handler(req, res) {
const { method, body, cookies } = req;
const { userAuthToken } = cookies;
console.log({ cookies });
console.log({ userAuthToken });
``// ...
}I
In src/pages/tasks/index.js
i use getServerSideProps
to fetch tasks from src/pages/api/tasks
:
export async function getServerSideProps() {
const URL = process.env.NEXT_PUBLIC_TASKS_API_URL; // localhost:3000/api/tasks
const response = await fetch(URL);
const tasks = await response.json();
return {
props: {
tasks: tasks.error ? [] : tasks
}
};
}
Now: When i enter to localhost:3000/tasks
, in backend terminal is shown:
( cookies not defined )
But, when i enter to localhost:3000/api/tasks
the backend terminal shows:
( cookies defined )
Neither HTTP-only nor 'public' cookies are logged in console when i enter to client tasks route ( localhost:3000/tasks
), but when i enter to API route ( localhost:3000/api/tasks
) they are logged in backend console normally.
Also, i have a middleware.js
in src
, but i tried removing it and there wasn't difference:
import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
export async function middleware(req) {
const { cookies, url } = req;
const authToken = cookies.get("userAuthToken");
if (authToken === undefined) {
const urlToRedirect = new URL("/login", url);
return NextResponse.redirect(urlToRedirect);
}
try {
await jwtVerify(authToken, new TextEncoder().encode("secret"));
return NextResponse.next();
} catch (error) {
console.error(error);
const urlToRedirect = new URL("/login", url);
return NextResponse.redirect(urlToRedirect);
}
}
export const config = {
matcher: ["/tasks/:path*", "/dashboard"]
};
This middleware is only executed in /tasks/
and /dashboard
. Logs to the console from here are always shown correctly.
Any help is appreciated. Thanks so much!