It took me something like eight hours to understand how to bring Next.js 13 Beta to let a user put text into an input field and use that text in a function. Here’s why:
- The component has to be client-side for a state driven input field to work.
- The function had to be invoked server-side because it uses an (OpenAI) API key that would have otherwise been exposed.
I tried for hours to somehow manage to take the string from the input field and throw it into the server rendered component. That doesn’t even make any sense and was always going to fail. It would be a paradox.
It took me only a couple of hours to come to that conclusion. That’s when I figured that Route Handlers, formerly known as API Routes might be the solution. There was only one problem: I didn’t really understand what they are, what they’re doing and what exactly they’re meant to be used for. After playing around with them for a while, I somehow lost my mind and went back to my initial approach: Trying to convince a server side component to dynamically render something based on data from a client side component.
That, and this might come as a surprise, still didn’t work. It was only after asking on Mastodon that somebody pointed me in the right direction. Yes, Route Handlers are the right tool for the job and yes, a POST request is what I needed.
It took me only three more hours to understand what HTML request methods are, where to put them in Next.js, how to define a request, how to return something from the POST method back to where it was fetched and how to handle the asynchronicity of it.
A few random thoughts:
- I thought Route Handlers are only used to create an API for the product you’re building. For external applications to get access. It took a long while until I understood that they’re also, if not primarily, used internally. The client side part of my app talks to the server side part of itself. That’s still somehow a weird concept to me.
- I don’t fully grasp HTML request methods yet. Conceptually I understand what they’re doing but I can’t wrap my head around what’s needed inside of the object you send with a POST request. There’s a header, a body, some other stuff but only sometimes. My function only needs the URL, the method and a body. Others seem to require a lot more stuff and in a different format. No idea where these rules come from but I’ll figure that out at some point.
.then().then().else().hurr().durr()alternate universe that’s going on there.
- All of this gave me a better understanding of how Next.js works. I feel like I now understand what’s supposed to happen where. Route Handlers might have been the missing key. I don’t understand them completely yet but that’s only a question of time now that I know when to use them.
I think it’s funny that the complicated part wasn’t to use the API for one of the most sophisticated AIs available but to understand even more intricacies of web development.