Yuval Zarfati
Yuval Zarfati

Reputation: 11

Nextjs: can't get httponly cookie inside getServerSideProps using Laravel

I'm developing a website using laravel as my API and using nextjs as my frontend. When a user login I make a post to my laravel API in order to authenticate him. If successful, I return an httponly cookie with the response containing the auth token. After login I want to navigate the user to the home page. I created a wrapper function for getServerSideProps so that each page that need to check auth will do so with that function, if the token is not in the cookies or expired, redirect to the login page. In this wrapper function I try to get the req.headers.cookie but I get undefined.

This is my laravel endpoint:

    public function login(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'username' => 'required|string',
            'password' => 'required|string',
            'rememberMe' => 'boolean|required'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $loginData = $validator->validated();
        $credentials = $loginData;
        unset($credentials['rememberMe']);

        $usersModel = new Users();
        $user = $usersModel->get_user_by_credentials($credentials);

        if (!$user) {
            return response()->json(['error' => 'Unauthorized', 'msg' => l('LOGIN__incorrect_details', 'login_lang')], Response::HTTP_UNAUTHORIZED);
        }

        if (empty($user['status']) || $user['status'] != '1') {
            return response()->json(['error' => 'Not Active', 'msg' => l('LOGIN__account_suspended', 'login_lang')], Response::HTTP_UNAUTHORIZED);
        }

        $token = auth()->login($user);
        $response = $this->createNewToken($token);
        $cookie = Cookie::make('auth', $token, $loginData['rememberMe'] ? env('REMEMBER_ME_TTL', 525600) : env('JWT_TTL', 60), null, null, App::environment('production'), true, false, App::environment('production') ? 'none' : null);

        return $response->withCookie($cookie);
    }

This is my withAuth wrapper function and an example for the home page:

import { GetServerSidePropsContext } from 'next';
import { ParsedUrlQuery } from 'querystring';

export function withAuth(
    gssp: (context: GetServerSidePropsContext<ParsedUrlQuery>) => Promise<any> = async () => { return { props: {} } }
) {
    return async function (context: GetServerSidePropsContext<ParsedUrlQuery>) {
        const { req } = context;
        console.log('req.headers.cookie', req.headers.cookie); // undefined

        return await gssp(context);
    }
}
import { withAuth } from "@/lib/with-auth";

export const getServerSideProps = withAuth();

export default function Home() {
    return (
        <></>
    );
}

I tried setting the cookie samesite value to none and null, nothing changed by this.

All of this was tested only on development environment. If anyone knows How I can get the auth token inside getServerSideProps in order to validate the user It will be amazing.

Upvotes: 0

Views: 121

Answers (1)

Yuval Zarfati
Yuval Zarfati

Reputation: 11

After hours of trying, just minutes after posting the question, I found an answer. What solved it for me is that I didn't use {withCredentials: true} with my axios request.

Upvotes: 0

Related Questions