Next.js Discord

Discord Forum

NextJS API Route error

Unanswered
Giant Angora posted this in #help-forum
Open in Discord
Giant AngoraOP
This is the code under app/api/db/user/route.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async (req:NextApiRequest)=>{
console.log("API HIT");
switch (req.method) {
case "POST":
console.log("API HIT");
break;

default:
break;
}
const reqBody = req.body;
console.log(reqBody)
}


And in component calling api like this:

if (isNewUser) {
// YOU ARE A NEW USER"
await axios.post("api/db/user", user);
}



ERROR:


Uncaught (in promise)
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
:
"ERR_BAD_REQUEST"
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
"Request failed with status code 404"
name
:
"AxiosError"
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: '<!DOCTYPE html><html id="next_error"><head><me…self.__next_f.push([1,""])\x3C/script></body></html>', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}
stack
:
"AxiosError: Request failed with status code 404\n at settle (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/adapters/xhr.js:125:66)"
[[Prototype]]
:
Error

103 Replies

@Giant Angora This is the code under app/api/db/user/route.ts import type { NextApiRequest, NextApiResponse } from 'next' export default async (req:NextApiRequest)=>{ console.log("API HIT"); switch (req.method) { case "POST": console.log("API HIT"); break; default: break; } const reqBody = req.body; console.log(reqBody) } And in component calling api like this: if (isNewUser) { // YOU ARE A NEW USER" await axios.post("api/db/user", user); } ERROR: Uncaught (in promise) AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 404" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response : {data: '<!DOCTYPE html><html id="__next_error__"><head><me…self.__next_f.push([1,""])\x3C/script></body></html>', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …} stack : "AxiosError: Request failed with status code 404\n at settle (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///(app-pages-browser)/./node_modules/axios/lib/adapters/xhr.js:125:66)" [[Prototype]] : Error
export async function POST(request: Request) {
  const data = await req.json();
  console.log(data);
  return Response.json({})
}

you should create the route handler like this in app router
https://nextjs.org/docs/app/api-reference/file-conventions/route
Giant AngoraOP
@Ray same error
status code 404?
and are you fetching it in server component?
if so, you need to use absolute url http://localhost:3000/api/db/user instead of /api/db/user.
however, you should fetching own api in server component
https://nextjs-faq.com/fetch-api-in-rsc
Giant AngoraOP
@Ray Actually I want to set firebase functions in api route files, here if user is new I want user to add into firebase cloud store. For that I am implementing this into api route
if it is a server component, you don't need api route for that
or if you are doing it in client component
also, I think it is better to be done in the login function?
Giant AngoraOP
So you are saying I should make a seperate firebase dir, two seperate files in that: authentication.ts and db.ts. managing respective functionalities
Like I should addUser functionality in db,ts file and call the function in login after authentication
yes I think it is better, are you doing this with firebase auth?
Giant AngoraOP
yaa
I only need to authenticate user, then add user if its new then update its profile based on the form details. Do you think I should use api
You could create a signin server action with firebase admin, and add the user info to firestore after the registration
Giant AngoraOP
@Ray Can you give me more details about it. Like I have used the firebase firestore for CRUD operations and authentication. But all this was client side operation. How to initiate server action
how are you doing authentication now?
Giant AngoraOP
@Ray google sign In and email/password authentication
@Giant Angora <@743561772069421169> google sign In and email/password authentication
// action.ts

"use server";

import { getFirestore, doc, setDoc } from "firebase/firestore";

export async function createUser(authId: string, data) {
  const db = getFirestore(app);
  await setDoc(doc(db, "users", authId), {
    ...data
  });
}
you can create a server action like this, and call it right after the google login callback
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
import {createUser} from 'action';

const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
  .then((userCredential) => {
    // Signed in 
    const user = userCredential.user;
    await createUser(user.id)
    // ...
  })
  .catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
  });
something like this
Giant AngoraOP
@Ray thanks for this. But I have a question what are its benifits over calling function like if I have db file in that I have createUser. "not using use server"
I think you can use your existing createUser function by puting use server on top to make it a server action
Giant AngoraOP
What are its pros, like using use server
so you don't need to create an api route each function
and everyone can try to access the api route if they know the path
Giant AngoraOP
Could you please elaborate🥲 . Its getting over my mind.
what do you need
Giant AngoraOP
Please check the folder structure, in firebase/db I have addUser functionality, using directive "use server". What it will do and if I remove this directive simply call this function what will that do
Client Components can only import actions that use the module-level "use server" directive.

To call a Server Action in a Client Component, create a new file and add the "use server" directive at the top of it. All functions within the file will be marked as Server Actions that can be reused in both Client and Server Components:
move use server to the top of the file
then you can import it to the client component
without it, it will cause an error
Giant AngoraOP
Like this, anything else I have to change?
look good, try it
Giant AngoraOP
how are you using it
Giant AngoraOP
this googleSignInFunction will invoke after clicking button
can you liveshare?
Giant AngoraOP
sure
wait 1 min
you got error when using google sign in?
Giant AngoraOP
yaa
you can chat in session chat vs code
i think it should work now
can you try
btw, I just signed in with my google account, you can delete me after
Giant AngoraOP
Please wait
Same error
You are added but if its a new user it should be added in DB as well
But you arent added in DB
ok let me see
the isNewUser from getAdditionalUserInfo is false
Giant AngoraOP
have logged in second time
?
yes
Giant AngoraOP
Let me delete your id in firebase panel, then try again
Now try
again
ok
Giant AngoraOP
Now what was it this time
same error
delete me again
Giant AngoraOP
wait
Now try again
I am getting true for new user
do you see new user in db?
Giant AngoraOP
wait
No
Giant AngoraOP
Do it again, there was some confusion as I was also trying to login
I have deleted your id
Login again
ok
do you see it in db
Giant AngoraOP
yaa, it worked
what was I doing wrong?
it cause error because you were using firebase in a server environment
now, i commented out the use server
which mean it is doing on client
you should do it with firebase-admin
Giant AngoraOP
Is this having all functions available, which are available on web
you need to use firebase + firebase-admin
and firebase-admin for this kind of operation
for the security reason
Giant AngoraOP
Is it worth to perform server actions,
yes
Giant AngoraOP
I mean what are the pros
firebase-admin need to run with server action or api route
you can do it with api route
but you need firebase-admin either way
Giant AngoraOP
ok. BTW thanks for the help, means alot. Hopefully discussing more on this. Its 2 AM almost here. Will be discussing in detail tomorrow
ok np
I usually use a cloud function for this, adding a user to db after registration
Giant AngoraOP
I will explore this as well thanks!
Tommorow will be discussing more