I've recently added an example with cookie auth which explains what you are trying to do on the frontend.
For the backend, optimally you'll have your API in an external server, apart from the server you use for rendering your Next.js app. This API will handle the database and the token creation business. Then the basics of the authentication are like this:
- The client
POST a request with username and password to the server.
- The server gets the request and generate a token based on the data received.
- If everything went okay validating the data, the server responds with the token, e.g.,
{ token: "secrettoken" }.
- The client receives the token and saves it in a cookie. Optionally you redirect the user to the
/dashboard or /profile if everything is okay.
- The client, on restricted pages, will check if the cookie exists and optionally validate that against the server, you do this last part in
getInitialProps. If the cookie validation fails you redirect the user away.
I've created a small library to abstract this logic.
So in the end, your Next.js app shouldn't know what's happening in the server, it only should receive the token, save it, validate it, and redirect the user if something is wrong.
How you want to handle the token creation, on the external server, is up to you.