Same types in frontend and backend
Unanswered
Naeemgg posted this in #help-forum
NaeemggOP
Assume I have a route handler
And here is the client component where I'm making request to it:
All I'm trying to say is how to give type to both frontend and backend the same, like here I wont get any error in build time by not passing the required data to backend but I'll get the errors in runtime. Is there any solution to it?? I'm thinking of making a file something like
/api/post-data below is its route.ts file:import {type NextRequest, NextResponse } from "next/server";
export const POST = async(req:NextRequest)=>{
const {name,email} =await req.json();
//DO something with the email address and password here.....
const data = "Result value from above calculations"
return NextResponse.json(data,{status:200})
}And here is the client component where I'm making request to it:
"use client"
import {useState,useEffect} from 'react'
const ClientComponent = () => {
//some useState...
//useEffect()...
const handelFetch = async()=>{
const response = await fetch("/api/post-data",{
method:"POST",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({email}), // "name" IS REQUIRED BUT NOT PRESENT
})
const data = await response.json()
setData(data)
}
//...
return (
<div>
{/*bla bla bla */}
</div>
)
}
export default ClientComponentAll I'm trying to say is how to give type to both frontend and backend the same, like here I wont get any error in build time by not passing the required data to backend but I'll get the errors in runtime. Is there any solution to it?? I'm thinking of making a file something like
types.ts and export types for it and assign it to both CC and route handler. Please let me know if there's a easy way to tackle this.