E
E
Ebers-Hyde2021-12-03 17:19:40
PHP
Ebers-Hyde, 2021-12-03 17:19:40

How to implement authorization in next application using api yii2?

Good afternoon. I'm in the process of learning next.js/reactand creating a project based on next (frontend) and php-framework yii2 (back). For the third week now, I have been at a complete dead end and cannot do a normal authorization through the rest. By itself, I established a connection between them, I can get data from api. But in some places, I need to immediately render user data, if it is present (first of all, this is a header with the username of the user, and then the number of goods in the cart will be added). The nuance is that the back takes the / api route, which the next needs to communicate with the server. Therefore, I have to write authorization myself without using libraries. At first, after logging in, I tried to save the username in the browser cookies and when loading the application, if it exists, render the header with it, but this breaks my layout due to the fact that that the cookie is not visible on the server, which means that the page is formed according to one template, and on the client it tries to substitute data. Then I decided to save the auth_token in cookies and get the username in _app.tsx using the getInitialProps method, based on the articlehttps://jools.dev/server-side-auth-with-nextjs-con... . However, there are no cookies in the application context either, which causes the request to fail. For greater clarity, I uploaded the front of the project to codesandbox - https://codesandbox.io/s/applecart-next-o9u4v The thing is that there are cookies inside myApp.ctx.req.cookies if you print them to the console, but on mine the server no longer exists.

Those who know, please tell me how in this situation I can achieve storing cookies and reading them to obtain the necessary data during the initial rendering?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2021-12-06
@SilenceOfWinter

The nuance is that the back takes the / api route, which the next needs to communicate with the server

well, don't take it, what's the problem? besides, nextjs routing is not related to yii routing,
you can try this option
https://ru.wikipedia.org/wiki/JSON_Web_Token
https://github.com/sizeg/yii2-jwt
https://github.com/vercel/examples /tree/main/edge-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question