phplaravelauthenticationnext.js

Connecting NextJS frontend with laravel backend


I am using nextjs frontend to connect laravel backend that has rest apis. I am having problem in authentication of a route. At the login time response contains jwt token and I am storing that in localStorage. The public apis are working great but protected apis are not working as I am not able to provide jwt in headers. I am using axios to make requests along with react-query.

api.js `

import axios from "axios";
if(typeof window !== "undefined"){
    var token = localStorage.getItem("token");
}

const api = axios.create({
    baseURL: "http://<server ip address>:8000/api/v1/",
    headers: {
        "Authorization": `Bearer ${token}`
    }
});

export default api;

` request

const {data, isLoading, isError, error, isSuccess} = useQuery("user", getUser);

getUser

import api from "@api/index";

const getUser = async () => {
    try {
        const res = await api.get("user/me");
        return {status: res.status, data: res.data};
    } catch (error) {
        if(error.response && error.response.data.message){
            return {status: error.response.status, message: error.response.data.message};
        }else{
            return {message: error.message};
        }
    }
}

export default getUser;

When I checked network tab. I got authorization: "Bearer null" in request header. Is there anyway to do this. Thanks in advance.

I thought there is a mistake in getting token so I conditionally made query to localStorage. you can see in api.js. But it is still null.


Solution

  • I found a way:

    Now I am storing the token in cookies with the help of cookies-next npm package. You can also do it without this package

    Since it is stored in cookies, I can access that inside getServerSideProps from context.req.cookies.cookie_name or if you are also going to use cookies-next, you can do getCookie("cookie_name", {context.req, context.res}).

    :)