Next.js Discord

Discord Forum

How can I use the REST API I created with Laravel in my Next.js application?

Answered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Dwarf CrocodileOP
I'm really confused. How can I use the REST API I created with Laravel in Next.js? Should I use actions or route handlers? What methods and libraries can help me?
Answered by James4u
My pleasure, feel free to mark as a solution. Also check this out when you have time
https://next-safe-action.dev/
View full answer

48 Replies

@Dwarf Crocodile , if you are using app router, you can hit that api in your server component directly
no server actions or route handlers needed!
not talking about the parallel data fetching but as you can see you can fetch data from any external apis directly in your server component
Dwarf CrocodileOP
I am very confused about operations like post and delete. I am also using the React Query library to handle this.

My application is as below, at least for now I am able to use the project to make API requests πŸ™‚ I hope I will get used to it slowly.

export default function LoginForm() {
    const router = useRouter();

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm({
        resolver: yupResolver(loginValidationSchema),
    });

    const mutation = useMutation({
        mutationFn: async (data) => loginFetch(data),
    });

    const onSubmit = async (data) => {
        const { status, message } = await mutation.mutateAsync(data);

        if (status) {
            toast.success(message, {
                onClose: () => {
                    router.push("/");
                },
            });
        } else {
            toast.error(message);
        }
    };
oh, you are using ReactQuery then it must be different.
in app router, it's highly recommended to use server actions for data mutation
if you want to keep your react query stuff, yeah, you have to have your api routes which you can hit from your react query
so in your case, you should have /login api route
however I still recommend you to check server actions for data mutation
Dwarf CrocodileOP
I created the api with laravel.
it's not an issue
in server actions, you can use your laravel backend
Dwarf CrocodileOP
When I used server actions, I had difficulty in form validation processes etc. on the client side. Let me research these issues a little more. thank you πŸ™‚
@James4u in server actions, you can use your laravel backend
Dwarf CrocodileOP
Do you mind if I use react query now?
okay then what's the trouble with your current implementation
as it's client side data fetching, you can't access to env.API_URL I guess
it should be NEXT_PUBLIC_API_URL no?
@James4u okay then what's the trouble with your current implementation
Dwarf CrocodileOP
There is no problem now, if the methods I use in my current application are not wrong, there is no problem πŸ™‚ I was wondering how to use the api I created with laravel in the most logical way.
authServices.js
oh, it was a server action, lol previous screenshot didn't show me "use server"
oh yeah, you are using your laravel backend in your server actions
you are going in the right path I would say
Dwarf CrocodileOP
Thank you very much ❀️ I needed advice from someone who knew, otherwise I was very confused.
Original message was deleted
My pleasure, feel free to mark as a solution. Also check this out when you have time
https://next-safe-action.dev/
Answer
Dwarf CrocodileOP
It's great. πŸ™‚ ❀️ Take care of yourselves
Dwarf CrocodileOP
@James4u

Sorry to bother you.

There's something I'm curious about. I get the information of the logged in user by sending a request with fetch on the server side.

export async function getLoggedInUser() {
    return await fetcher("profile");
}


I can use this function in server side files as follows.

const { name } = await getLoggedInUser();


How can I use this on the client side?
Nope @Dwarf Crocodile you can't. you can NOT perform server-side data fetching in the client side
@James4u Nope <@1235010908229603431> you can't. you can NOT perform server-side data fetching in the client side
Dwarf CrocodileOP
import { getLoggedInUser } from "@/services/authServices";
import React from "react";

// Server side
const fromServer = async () => {
    return await getLoggedInUser();
};
// Client side
export function useAuth() {
    const [user, setUser] = React.useState({});

    const getUserData = async () => {
        const userData = await getLoggedInUser();
        setUser(userData);
    };
    React.useEffect(() => {
        getUserData();
    }, []);

    return user;
}

useAuth.fromServer = fromServer;


I applied such a simple method. I can call and use it on both server and client, it seems to work for now πŸ™‚
can you show me getLoggedInUser?
Dwarf CrocodileOP
I get the information of the logged in user by sending a request to the Laravel api.
But I have a question, is it a problem to send requests like this every time, for performance, etc.?
what's the fetcher like?
Dwarf CrocodileOP
lol it was
yeah it can be used in the client side
but it's not correct to use that fetcher in the server side
is API_URL your next.js api host?
Dwarf CrocodileOP
laravel address
oh, I remember sorry forgot our conv
Dwarf CrocodileOP
can't I use it on the server side
does your cookie logic work?
Dwarf CrocodileOP
yes everything works smoothly
@Dwarf Crocodile can't I use it on the server side
?? what's this?
@James4u but it's not correct to use that fetcher in the server side
Dwarf CrocodileOP
for this
thought that it was your next.js api route
Dwarf CrocodileOP
ah okey πŸ™‚
thank you for your answers ❀️