No video

Next.js API Routes Validation using YUP: Share frontend and backend validation using YUP schemas

In this video we will add validation to our Next.js API Routes using YUP. In order to achieve that in a simple and reusable way we will create a validation middleware that uses YUP for schema validation.
Because we are using YUP, we can now share our validations across front-end and back-end. Form libraries like formik and react-hook-form work very well with YUP.
I hope you enjoy the video :)
--- URLs
GitHub URL: github.com/bmv...
GitHub commit history: github.com/bmv...
Video introduction to Next.js API Routes: • Next.js Tutorial - Par...
Video using next-connect (Express like API): • Next.js API Routes usi...
Next.js Tutorial Playlist: • Next.js Tutorial
YUP documentation: github.com/jqu...
HTTP Verbs/Methods description: restfulapi.net...
---- Timeline:
00:00 Introduction
01:23 Yup validation schema description
02:00 Yup string validation
02:28 Yup number validation
02:58 Yup email and url validation
03:30 Yup array validation
05:23 Infer TypeScript interface/Type from the Yup validation schema
06:15 Validate using the schema
07:44 Why/How create a validation middleware for the Next.js API Routes
09:00 Code starts
09:25 How to create a middleware in Next.js API Routes
11:52 Use Yup inside our Validation middleware
13:42 Remove unwanted properties from our objects using yup
14:34 Make yup validations strict by the type
15:15 Convert any case to camelCase, for example personal_website to personalWebsite
16:49 Show all validation errors, not only the first (abortEarly: false)
17:37 Extend our schemas with ID for our put methods without having to pass two different schemas to our middleware
21:14 Copy validation middleware to its own file
22:10 Recommend next-connect to avoid switch case in our API routes
23:12 Outro
----
Follow me on:
Twitter: / bmvantunes
Dev.to: dev.to/bmvantunes
Website: brunoantunes.net
GitHub: github.com/bmv...
LinkedIn: / bmvantunes

Пікірлер: 134

  • @Kevin-yw5qr
    @Kevin-yw5qr3 жыл бұрын

    Hi Bruno, I know your channel isn't huge or anything at this moment in time, but your content is fantastic and super easy to follow along with. I really do appreciate the work you're doing and I hope you continue putting out these tutorials going forward. Much appreciated.

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much Kevin 😍 words like that give me motivation to keep going, thank you, thank you😊🤩

  • @thetpaingmyo8448
    @thetpaingmyo84483 жыл бұрын

    underrated channel

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you 😍 Hopefully one day we will grow 😅😅😅

  • @robertmarriott3227
    @robertmarriott32272 жыл бұрын

    I'm trying to DRY up my Next.js project and this is **exactly** what I was looking for! Thanks, Bruno!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    I'm very happy to know that 😍 this is a pattern I use quite a lot in my applications. Being able to use the same exact validations in the client and server is amazing 😍

  • @shrestha0144
    @shrestha01442 жыл бұрын

    This was exactly what I was looking for and you earned a subscriber

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    Thank you very much 😍😍

  • @slipkn9
    @slipkn92 жыл бұрын

    tks to bring that content, and tks to yup to make this library. It's good when the mistakes are showed =D

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    Thank you

  • @tririfandani1876
    @tririfandani18763 жыл бұрын

    Clean presentation and clear explanation. As always 👍 👍

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much for your words 😍😍 very happy you enjoy my videos ♥️♥️

  • @DEV_XO
    @DEV_XO3 жыл бұрын

    As I said in some other comment, would be amazing if u keep uploading this kind of videos for NextJs. We all know NextJs will hit hard this year, so... content like this, tips and tricks are absolutly great! Also might be nice if u could create an "advanced" course, with some great tips. This channel has a bright future!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you for your support my friend 😍 what kind of tips are you looking for? 😅

  • @DEV_XO

    @DEV_XO

    3 жыл бұрын

    @@BrunoAntunesPT Tips like this one mate, a lot of us comes from express, this middleware stuff for next was an amazing discover. Would be cool, some advanced stuff, we all know react, so... learning some tricks and stuff for next would be cool!

  • @marc-andrequintal570
    @marc-andrequintal5702 жыл бұрын

    awesome, I very like the build approach you have to explain good job

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    Thank you very much 😍

  • @wiseman9960
    @wiseman99603 жыл бұрын

    Why cant I like this video more than once?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you soo much Radoslav ❤️❤️❤️ I'm very happy you enjoyed the video 😍😍

  • @oleksandr5128
    @oleksandr51283 жыл бұрын

    YUP, with Formik in the heart))

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    You can bet that Oleksandr! For me YUP + Formik = Love ❤️ ahah

  • @jordanimran5710
    @jordanimran57102 жыл бұрын

    Very, very well done, thank you

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    Thank you Jordan 😍

  • @hamed4451
    @hamed44513 жыл бұрын

    Thanks bro, i missed you and your awesome videos ❤

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you Hamed 😍😍 I think I'm starting to have more free time again ♥️♥️♥️

  • @mohdsahil226
    @mohdsahil2263 жыл бұрын

    Hi, Bruno, Thank you very much for your videos. They are awesome.

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much for your comment Mohd 😍

  • @mohdsahil226

    @mohdsahil226

    3 жыл бұрын

    @@BrunoAntunesPT Thank you Bruno for you quick reply. The video I ask you to make is nowhere I tried with examples provided by nextjs, but one I use that, it doesn’t preload pages

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    You are referring to next + redux persist? 😊 I don't use redux nowadays 😊 In the nextjs repository as you say they have some examples using redux, but I have been away from redux for a long time 😅

  • @mujin00
    @mujin003 жыл бұрын

    ありがとうございます!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much ❤️

  • @stannone7272
    @stannone72723 жыл бұрын

    easy! thx for explaining

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you Stan 😊

  • @jrs_devs
    @jrs_devs3 жыл бұрын

    Nice video as always Bruno. I've just tried the concat method and it's saved my life. Super useful for merging schemas which fields are different in the client forms and in the API (for example 'repeat password' and 'accept terms' fields). Do you know if the validate middleware can be used with next-connect?, I don't know if the schema could be passed to it.

  • @jrs_devs

    @jrs_devs

    3 жыл бұрын

    I reply to myselft: Yes, Schema can be include with next-connect. IN API: export default handler = nextConnect().use(validate(schema).post(...) Middleware: export default (schema) => async (req, res, next) => { if (['POST', 'PUT'].includes(req.method)) { try { req.body = await schema.validate(req.body, { abortEarly: false }); } catch (e) { return res.status(400).json({ error: e }); } } next(); }

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you Jorge 😀😀 Sorry, I only had a chance to see the comments now 😀 I'm very happy you found the answer 😀😀

  • @oguz-kagan
    @oguz-kagan3 жыл бұрын

    damn.. great tutorial thanks!!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you for the feedback 🙏😊

  • @mohamedyoussef8835
    @mohamedyoussef88352 жыл бұрын

    Awesome Tutorials ++++++++++++++ Thank You

  • @BrunoAntunesPT

    @BrunoAntunesPT

    2 жыл бұрын

    Thank you very much 😍

  • @JoeBoo532
    @JoeBoo5323 жыл бұрын

    awesome content, as usual, Bruno! :D I have a quick question and wonder if you could help. Have you ever tried to write a unit test for yup?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you 😀 yes, you don't unit test yup directly, you test your form 😊

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    That way if in the future you change to another validation library, ideally you don't need to redo your tests 😊that way you have confidence you didn't break anything. In this case is not a form, but the idea is exactly the same 😅

  • @JoeBoo532

    @JoeBoo532

    3 жыл бұрын

    @@BrunoAntunesPT That is what I've been doing! :D thanks, Bruno! keep rocking ✌✌

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you my friend. I have been putting some ideas in paper for a unit testing series 😀 very very very early stages, like an alpha release of a game, but it will happen on day in the future 😂😂😂

  • @JoeBoo532

    @JoeBoo532

    3 жыл бұрын

    @@BrunoAntunesPT you should do it! :D I'm definately will be keeping an eyes out on that series to see if I can pick a thing or 2 of you :D

  • @Shoutiez
    @Shoutiez3 жыл бұрын

    Hopefully you will make a series of nextjs + grapql :)

  • @edwinrafaelhenriquezh2085

    @edwinrafaelhenriquezh2085

    3 жыл бұрын

    and strapi

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    At the moment I've been looking into Prismic 😊 I heard a lot of amazing stuff about Strapi but never had the chance to test it out (maybe in the near future 😃)

  • @matiassal9763

    @matiassal9763

    3 жыл бұрын

    @@BrunoAntunesPT Did you mean Prisma? I am totally agree with that decision. Thanks!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    ​@@matiassal9763 I have also been moving some stuff away from TypeORM into Prisma. I still have some small concerns with Prisma, that's the only reason I don't have a video with Prisma yet =) Regarding Prismic it is a CMS - prismic.io/

  • @bernardamofah4524
    @bernardamofah45243 жыл бұрын

    Another great one

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Mister Bernard 🤩🤩 thank you very much mate 😀

  • @AlexandrePaiva-dev
    @AlexandrePaiva-dev3 жыл бұрын

    Hi Bruno, thanks for another great video! I'm wondering how I can use the property label inside the custom message? For example, something like: export const schema = object({ firstName: string().required(`${label} is required`).min(2).max(40).label("First name"), });

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much Alexandre 😊 If I understand correctly what you want, the closest thing I know is the fact you can override the default name/id in error messages: github.com/jquense/yup#mixedlabellabel-string-schema Not sure if that's what you want/need 😅

  • @briandevs
    @briandevs3 жыл бұрын

    Thanks Bruno!

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you very much for watching the video 😊

  • @rezaulmasum205
    @rezaulmasum2053 жыл бұрын

    Please make a tutorial on nextJS with redux and redux-persist. I did not find out any tutorial on it.

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    At the moment I'm not using (or recommending) redux. Because of that, I don't have any redux tutorial in my plans (we never know the future, but for now is not planned) 😊

  • @rezaulmasum205

    @rezaulmasum205

    3 жыл бұрын

    @@BrunoAntunesPT which state management do you prefer for state management ?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    As always... it depends on your use case 😅 there's no one size fits all. Read what I'm going to say with a grain of salt: For most of the stuff we do in webapps usually useSwr and context are enough 😊 When I'm dealing with something complex that I can model as a state machine I can 100% recomend xstate 😊 github.com/davidkpiano/xstate

  • @Marcus-09
    @Marcus-092 жыл бұрын

    hi, nice video. How can i validate a date with yup? i'm stuck and i tried with momentJs, but nothing...

  • @monicasilvestre1699
    @monicasilvestre16993 жыл бұрын

    ❤️

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    ❤️❤️❤️

  • @valentincostam
    @valentincostam Жыл бұрын

    Hi Bruno. I love your videos. Thank you so much for this one. I'm using this approach for validating the data but I found a problem with it. When I try to update a record sending only its modified values, I get a validation error because some required fields are missing. How do you avoid this? Do you have two schemas, one for creating (POST) and the other for updating (PUT)?

  • @_sumitdey.exe1
    @_sumitdey.exe13 жыл бұрын

    Hey Bruno! Great video. what will be the type of the handler if we use "next connect" handler...I can't find anything :)

  • @_sumitdey.exe1

    @_sumitdey.exe1

    3 жыл бұрын

    Hey...got it :) It's NextHandler :)

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Sorry for the delay my friend 😀 I'm very happy you found the solution 😊😊😊 I was editing tomorrow's video about conditional props with React and typescript 😀😀😀😀

  • @mohdsahil226
    @mohdsahil2263 жыл бұрын

    I am stuck with NextJS and Redux-Saga Persist. Would you please help?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    I'm sorry to hear that my friend. In the nextjs github repository they have (I think) 10 or 11 examples with redux. None of those examples is what you want/need?

  • @noone-k7h
    @noone-k7h3 жыл бұрын

    thanks for this material, Do you know how I can validate a field with a rule that depends on itself? for example if I have a field called "name" and I want a rule to validate that if the "name" field is not empty, disable it?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you 😀 You can have fields that depend on other fields, but I never tried it on a field that depends on itself... The code should be similar to this: github.com/bmvantunes/youtube-2020-june-multi-step-form-formik/blob/master/src/pages/index.tsx#L45 Let me know how it goes 😊

  • @zyBRA3
    @zyBRA33 жыл бұрын

    Hi Bruno!! Is it possible to get it working without TypeScript?! Great job!! Tks

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you 😊 Yes, just remove the types and everything will work in jsx files as well 😊

  • @techno_abhishek8982
    @techno_abhishek89823 жыл бұрын

    Bruno, I want to validate if the email already exists or not in the DB. So I used this YUP's test() method like this: email: string().required("Please enter a valid email.").email("Please enter a valid email.").test("emailExists", "Email address already exists.", checkEmailExists), In checkEmailExists() method i call /api/checkEmail and return true or false. BUT ISSUE IS: • I want to run emailExists validation only if the required & email validation is satisfied • I don't want to make api call on every key stroke, is there any way to add debounce in formik or yup?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    I'm a bit confused. In this video I didnt use formik. Are you asking a more generic question not related with this video? 😊 If yes, let me know if what you want is this: github.com/jquense/yup/issues/503

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    You also have this one which is very similar github.com/jquense/yup/issues/851

  • @sw05d404
    @sw05d4043 жыл бұрын

    what about if i edit one field some think like datatable - inline edit then required fields requires that filled

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Like we created a special case for POST schema you can create a special case for PUT schema 😊 the idea is exactly the same 😊

  • @ismoilshokirov
    @ismoilshokirov3 жыл бұрын

    Mr. Bruno if it is possible could you make videos about testing of Next JS apps, like Jest or others

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Hello Ismoil 😊 At work I'm using jest and testing-library.com/docs/react-testing-library/intro/ Is that the "stack" you would like to see videos on? 😊

  • @ismoilshokirov

    @ismoilshokirov

    3 жыл бұрын

    @@BrunoAntunesPT yes please))

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    That's actually something that is on my radar for a long while 😅😅 I'll need some time to prepare something like that but you can expect it sooner or later 😊

  • @bernardamofah4524

    @bernardamofah4524

    3 жыл бұрын

    @@BrunoAntunesPT yes please

  • @neerajsinghtangariya2587
    @neerajsinghtangariya25873 жыл бұрын

    please make a video on nextjs authentication-related video

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Hello Neeraj, I already have 2 videos about authentication in this playlist: kzread.info/head/PLYSZyzpwBEWS3vaMHM8cCJv6qv6DNzzA9 Let me know if you like them 😊😊 In the future I might create a video with passport and/or next-auth. Any preference between the 2 methods? 😃

  • @neerajsinghtangariya2587

    @neerajsinghtangariya2587

    3 жыл бұрын

    @@BrunoAntunesPT Is there any video related login/signup using third party api...? Basically In my project for backend I'm using the Laravel and created some login and register api...Now I want to use those api with NextJs... So, now I'm searching for this type of video.....

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Yeah... I don't have any tutorial covering that specific use case 😊

  • @usmanmughal5916
    @usmanmughal59163 жыл бұрын

    Please add mongodb to this project and make api calls with swr , It will be really helpful

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    I'll keep that in mind 😉😉

  • @nicolajslvsten4978
    @nicolajslvsten49783 жыл бұрын

    how to present the errormessage from the server with html on the client?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    You'll receive the errors object in the body of the http response like any other response you do with fetch, for example 😊 you can then put that into react state and show to users 😊

  • @nicolajslvsten4978

    @nicolajslvsten4978

    3 жыл бұрын

    @@BrunoAntunesPT Ahh yes I tried it using form action="/api/foo" which does not seem to allow me to stay on the same page.. but using xmlHttpRequest I can stay on the page, get the data and set state. Thank you :)

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Awesome 😀

  • @gigakvachakhia4777
    @gigakvachakhia47773 жыл бұрын

    Aaa here's my burning question. What do you think about making a custom express server with nextjs like we do it with react? Can it be SSRed and deployed as easily as normal next project?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Well....you can do that, but it's not recommended :) One of the side-effects (if I can call it a side-effect) is that you no longer can deploy into vercel: nextjs.org/docs/advanced-features/custom-server The second "side-effect" is that you lose ASO (automatic static optimization) - This alone should be enough to try avoid having a custom server :) From their docs: "Before deciding to use a custom server please keep in mind that it should only be used when the integrated router of Next.js can't meet your app requirements. A custom server will remove important performance optimizations, like serverless functions and Automatic Static Optimization." I hope this answers your question :) If not, we can go a bit deeper :)

  • @gigakvachakhia4777

    @gigakvachakhia4777

    3 жыл бұрын

    @@BrunoAntunesPT thanks for the answer. Basically answers it all. We have a large size project which requires a good 'Seo relationship' and alot of backend structuring. At first creating server and client(nextjs) separately seemed like a good idea cause squeezing everything into an app folder quickly becomes a mess. What would you recomend?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    I have been working in large nextjs projects and I don't find it a mess, quite the opposite. I love the fact that my routes are mapped on the file system, so I don't spend time navigating my files, which is a huge time savior for me 😊 I guess it all depends on how you organize your application code 😊

  • @gigakvachakhia4777

    @gigakvachakhia4777

    3 жыл бұрын

    @@BrunoAntunesPT thanks alot. It was helpful. Love ur channel ✌✌

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Thank you @@gigakvachakhia4777 😍

  • @siamekanto
    @siamekanto3 жыл бұрын

    What Font are you using in your editor?

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Default vscode font 😊 the only difference I have here is that I have zoomed it a fair bit, but this is default vscode 😊

  • @siamekanto

    @siamekanto

    3 жыл бұрын

    @@BrunoAntunesPT Oh, for some unknown reason, your default Consolas font looks way more beautiful than my Consolas font. 😢

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Oh really? 😅 Can it be related with the fact I record in 4k and the font seems a bit more smooth? My editor says on the font "Consolas, 'Courier New', monospace" - - - is that what you have as well? 😊

  • @siamekanto

    @siamekanto

    3 жыл бұрын

    @@BrunoAntunesPT Yeah, mine is same too. Oh right, 4K resolution might be the reason why your font looks a lot more smoother. Thanks for clearing the confusion! By the way, I have recently come across your videos and I absolutely love it. I love the way you explain things. You are Amazing Bruno! ❤

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Wowwww 😍😍 soo nice to read that Siam, thank you very much 😀😀

  • @mostaphaamghare313
    @mostaphaamghare3133 жыл бұрын

    In the next js, the same code runs in both the front end and the server. Does that not make it slow

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    This video is only about api routes, they only run on the server 😊

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    Or your are asking nextjs in general?

  • @mostaphaamghare313

    @mostaphaamghare313

    3 жыл бұрын

    @@BrunoAntunesPT nextjs in general

  • @mostaphaamghare313

    @mostaphaamghare313

    3 жыл бұрын

    for example context api it should be run just in client right? but in nextsjs it runs in client and server

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    It runs on your server at runtime before requests ONLY IF you use getInitialProps or getServerSideProps. If you use getStaticProps or normal components without any of those mentioned fetching methods, it only runs at build time in your build not runtime. The result is that it will be very very fast 😊 faster than your typical create react app 😊

  • @loadview
    @loadview3 жыл бұрын

    i dont understand anything please help

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    What do you need help on? 😊 Is there a video I can do to help??

  • @loadview

    @loadview

    3 жыл бұрын

    @@BrunoAntunesPT yes please like showing us step by step how to fix Yup to work again PLEASE

  • @BrunoAntunesPT

    @BrunoAntunesPT

    3 жыл бұрын

    What do you mean by work again? Can you elaborate? 😊