Secure API Authentication with NextJs: Client-Side vs Server-Side API Calls
Secure API Authentication with NextJs Series
4. Routing Microservice to the Same Port (optional)
When calling APIs, you will need a slightly different setup on the client-side vs server-side. Client-side, cookies will be sent with the request, however, on server-side our authentication stored in cookies has to be passed them manually.
Simple POST function
Consuming Token in API
From article (2), Set-Cookie from API, an accessToken
should be set in the cookies. On the client-side, when the above post method is called, the accessToken will be available in the request headers under request.headers.cookie
.
In your API, to parse the cookies into an object where you can access the keys, you can use the below helper function.
From here you can verify the token is valid using the jsonwebtoken library.
Extending POST for Server-Side
If making a server-side call e.g. getServerSideProps
, cookies are not automatically sent with each request. Therefore, we need to extract the cookies from the context and pass it to our API call.
The below function can be used for both server-side and client-side to retrieve cookies as a useable object. If the request context is provided, it will parse the cookies from the headers, otherwise, it will attempt to get cookies from document
.
Next, we need to extend our post
function so an access token to be passed. We are going to pass it in an Authorization
header.
Finally, we can make the API call from server-side.