Hey all, I am setting up Supertokens with Next.Js ...
# support-questions
r
Hey all, I am setting up Supertokens with Next.Js project and Flask. So my backend APIs' are running on Python flask on Http://localhost:5000/ and Next.js App is running on http://localhost:3000/. Using Managed service as Core. Followed Next.Js steps and can see the login page but when trying to signup or login I am getting CORS errors. Questions: Do I need any changes to Flask to make backend work or not? How to fix CORS errors? Please advise. Thanks in Advance.
Hey all, I am setting up Supertokens with Next.Js project and Flask. So my backend APIs' are running on Python flask on Http://localhost:5000/ and Next.js App is running on http://localhost:3000/. Using Managed service as Core. Followed Next.Js steps and can see the login page but when trying to signup or login I am getting CORS errors. Questions: Do I need any changes to Flask to make backend work or not? How to fix CORS errors? Please advise. Thanks in Advance.
r
hey @User , since you are not using nextjs' API folder, you need to follow the frontend setup fro nextjs only and then quick setup > backend for flask setup. That page has instrs on how you need to handle CORS
If you tell me which recipe you are using, I can send you a relevant links
r
Thanks @User, I am using EmailPassword recipe
r
Got it. So in the NextJS app, remove everything to do with supertokens-node lib. And instead, for backend, follow this https://supertokens.com/docs/emailpassword/quick-setup/backend
(There is a tab for python in those docs)
r
Is there a way that I can use my existing users db with supertokens for auth ?
r
Yes! You can use our override feature (see advanced customisation section) to change the sign in logic to use your own db for old users.
If you need more details on how to do that, I can send you some pseudo code when you are implementing that part
r
Sure, I would need that. I will try to follow those steps and meanwhile if you can send me that steps would be a great help
r
Okay. One question, for existing users, would it be okay with you if their userIds would change? Or do you want to continue to use their existing user id?
Allowing their userId to change will be simpler to implement for you from an auth point of view. But you would need to update all your other app tables with those new user ids
r
Keeping their userId would be important as there are many places where the userId is being used. And would be difficult to change those places.
r
Sounds good. I’ll write the logic that would maintain their user id
r
Awesome. I have an application that is using old flask version 0.2 and supertoken-python examples are from flask 2. Are there any examples that will work for legacy flask
r
No examples for that I’m afraid
But try and follow that. If you run into any issues, you can always ping me here
r
Thanks, I am following these steps and will come for help here. Really appreciate your help.
r
Happy to help 🙂
Also, do you mind sharing how you found out about us, why you picked us vs others and what’s your app domain that you plan on using us for?
Just for feedback 🙂
r
Thanks, I have found SuperTokens while searching for alternatives of auth0 or authentication flow.
My use case is to delegate the authentication flow to Supertokens
Looking for features to provide passwordless logins to impersonate customer account while investigating there account issue. I think I would use magic links in some way there.
r
Ah I see. So you want to also use our passwordless recipe
r
Yeah, that's the plan.
r
Great! So that being used to login to accounts owned by users who signed up with email / password will also require a tiny set of customisations. I can guide you through that too
r
We are using our custom session management at the moment but for new frontend apps we want some alternative to auth0.
r
I see. So you are currently using auth0?
If that’s the case, there is already a migration guide from auth0 to supertokens in the docs. In the email password recipe > migration section
r
Supertokens allows self hosted version hence we are thinking it as a strong contender
we are using auth0 partially but going forward have to either implement auth0 or alternatives
r
I see. Makes sense
I’ll write up the pseudo code for migration logic
r
Right now we have on-prem setup but roadmap is to move to AWS cloud. How hard/easy is to use Supertokens in AWS in this journey?
r
Not that difficult. Just run our docker container in an ec2 instance or using ECS. Connect that to your db. That’s it
If you have lots and lots of users, you can even add several of our containers, put it in front of a load balancer and that would scale
r
Ah Ok, So we can run Supertokens Core in Docker container there and possible utilize containerisation.
r
Yes
That would be the easiest way to run it.
You can also install supertokens via our zip file on any ec2 instance and run it using the CLI we provide
r
Legend 👍
r
Also, do mind sharing the company domain? Just curious
r
Our official company domain is precisionfarming.co.nz but most of the apps are running over VPN for employees only so won't be available outside of it.
I have installed supertokens-python 0.2 but InputAppInfo & SuperTokensConfig is not available in that package. any workaround?
r
You should use the latest version of supertokens-python
That’s version 0.4.0
r
Ah, I thought I would avoid to upgrade my python from 3.6 to 3.7 or more
r
oh.. so 0.4.0 doesn't work with the python version you are using?
r
Yeah, 0.4 only support >3.7
r
i think that's cause of fastapi support. Maybe try using it with flask? I think it should just work
unless it doesn't allow you to install it
r
Yeah, can't install 0.4, fallsback to 0.2
r
i see. Let me get back on this. Maybe the version constraint is not needed.
r
Ok
r
For account migration of existing users, see this: https://supertokens.com/docs/emailpassword/migration/from-auth0/account-migration/modifications-to-login Whilst the guide is for auth0 -> supertokens, the same logic applies from your custom auth -> supertokens. You just need to change functions like
doesUserExistInAuth0
to
doesUserExistInYourDB
and
validateAndGetUserInfoFromAuth0
to
validateAndGetUserInfoFromYourDB
.
The code snippets in that link are fro node js, but you can translate them directly to python. You will need to use the override feature of our supertokens-python SDK which you can learn about here: https://supertokens.com/docs/emailpassword/advanced-customizations/backend-functions-override/about
r
Awesome, thank you
r
hey @User it seems that we cannot support python < 3.7 at the moment. Would it be possible for you to upgrade the python version?
r
Yeah, I am in process of doing that. If it is successful I will continue with it
Thanks a lot for confirming
r
cool! If not, then there is still a way that you can use us via our nodeJS SDK. But it would be best for you try and figure out a way to make python work
r
So how nodeJS SDK works with API backend if I go with next.js API ?
Does it allow overriding config?
r
Yes. It allows all the features
So you would integrate our node SDK with the nextJS API layer (as the nextjs docs say), and then you can enable the JWT feature. This way, your frontend will get a JWT which you can send to the python process.
But then, things like customising the APIs we have to connect to your application db can be a pain cause you will have to replicate that logic in node...
r
Ah I see
r
hey @User did you get python SDK to work?
r
Hey @User, No I am getting this error:
Copy code
File "C:\git\ptnzapi\ptnz_api\__init__.py", line 14, in <module>
    from supertokens_python.framework.flask import Middleware
  File "C:\git\ptnzapi\venv37\lib\site-packages\supertokens_python\__init__.py", line 16, in <module>
    from .supertokens import Supertokens
  File "C:\git\ptnzapi\venv37\lib\site-packages\supertokens_python\supertokens.py", line 34, in <module>
    from .recipe.session.cookie_and_header import attach_access_token_to_cookie, clear_cookies, \
  File "C:\git\ptnzapi\venv37\lib\site-packages\supertokens_python\recipe\session\__init__.py", line 14, in <module>
    from typing import Union, Literal
ImportError: cannot import name 'Literal' from 'typing' (C:\Users\HansRajBhardwaj\.pyenv\pyenv-win\versions\3.7.9\lib\typing.py)
r
I see. @User can you please help with this?
r
Seems like it's not even 3.7 but 3.8 which is required python version
r
hmmm.
Did you try it with 3.8?
r
I am upgrading it to 3.8 now
@User I have got python SDK to a point where it is accepting requests but on signup or signin it is throwing this error:
Copy code
Are you sending too many / too few formFields?
I am making this request from login form
r
Can I see the supertokens backend and frontend config that you have set?
@User
r
Yeah sure, here is my backend config:
Copy code
init(
    app_info=InputAppInfo(
        app_name="Big Brother 3 Website",
        api_domain="http://localhost:5000",
        website_domain="http://localhost:3000"
    ),
    supertokens_config=SupertokensConfig(
        # These are the connection details of the app you created on supertokens.com
        connection_uri="https://d5bfb0117e4711ec9dc4c73b52b17527-ap-southeast-1.aws.supertokens.io:3570",
        api_key="my api key"
    ),
    framework='flask',
    recipe_list=[
        session.init(),  # initializes session features
        emailpassword.init(
            # TODO: See next step*/
        )
    ]
)
Copy code
app = Flask(__name__)
Middleware(app)

CORS(
    app=app,
    origins=[
        "http://localhost:3000"
    ],
    supports_credentials=True,
    allow_headers=["Content-Type"] + get_all_cors_headers(),
)
r
so you haven't added any extra form fields to emailpassword.init?
r
Copy code
import EmailPasswordReact from 'supertokens-auth-react/recipe/emailpassword'
import SessionReact from 'supertokens-auth-react/recipe/session'
import { appInfo } from './appInfo'


export const frontendConfig = () => {
    return {
        appInfo,
        recipeList: [
            EmailPasswordReact.init(),
            SessionReact.init(),
        ],
    }
}
Not yet, I haven't added extra fields
Do I need to add default fields like
email
and
password
to it?
r
you don't. Are you sending the API call manually? Or letting the supertokens' SDK make the call?
r
I tried both methods, same response.
Although, the CORS preflight request is still being blocked at frontend but I tried using POSTMAN as well as insecure browser to avoid CORS
r
Whats the CORS error?
r
Copy code
Access to fetch at 'http://localhost:5000/auth/signin' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
r
That's strange.. not sure why CORS lib isn't sending a proper reply.
It uses a diff recipe, but the overall setup is the same
is your's similar to that?
r
few diffs are: I haven't added providers to recipe, my api url has http protocol in it and no telemetry
I will try making same
r
Makes sense.. You don;t need providers cause you aren't using social login. http in api url is fine. no telemetry is fine too.
Any other ideas on why CORS isn't working as expected? Maybe you can create your own test API and try calling that from the browser - does that also fail the CORS check?
r
I will try a test API for CORS but the main concern is the API is not working from POSTMAN also. After parsing request API body is coming as blank
r
We will investigate that issue
r
that's what I found from initial eye on source code
Thanks
r
thanks
can i see the postman request you have made? For example, have you passed content-type as application/json in the header?
r
Copy code
curl --location --request POST 'http://localhost:5000/auth/signup' \
--header 'rid: emailpassword' \
--header 'Content-Type: application/json' \
--data-raw '{
    "formFields": [
        {
            "id": "email",
            "value": "test1234@gmail.com"
        },
        {
            "id": "password",
            "value": "test1234"
        }
    ]
}'
r
Hmm ok thanks.
@User we are working on fixing the above issues: - To get the SDK to work with python >= 3.7 - Investigating why the sign up issue is happening
k
Hey @User , we'll be releasing a patch update for python sdk to solve the python 3.7 issue soon. Regarding the signup and CORS issues, I tested with the following code along with auth-react example and it seems to be working as expected. Please try it out and let me know if you are still facing the issue
Copy code
python
from supertokens_python import init, get_all_cors_headers, SupertokensConfig, InputAppInfo
from supertokens_python.recipe import session, emailpassword
from supertokens_python.framework.flask.flask_middleware import Middleware
from flask import Flask
from flask_cors import CORS


init(
    supertokens_config=SupertokensConfig('https://try.supertokens.io'),
    app_info=InputAppInfo(
        app_name="SuperTokens Python SDK Testing",
        api_domain="http://localhost:9000",
        website_domain="http://localhost:3000"
    ),
    framework='flask',
    recipe_list=[
        session.init(),
        emailpassword.init()
    ]
)

app = Flask(__name__)
Middleware(app)
CORS(
    app=app,
    supports_credentials=True,
    origins="http://localhost:3000",
    allow_headers=['Content-Type'] + get_all_cors_headers()
)


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def index(_):
    return ''


app.run(host="0.0.0.0", port=9000)
r
Hey @User @User Thanks for the fix on python 3.7. I guess the problem is with flask version as well. I am using 0.12.2 version which might not support your
async
lib i guess.
I found that the workflow break at line 355 in supertokens.py at with this particular code
Copy code
response = await matched_recipe.handle_api_request(request_id, request, path, method, response)
@User In supertoken-node, do I need to start express server separately or it is started magically and what port it will run api on?
r
@rajhans84 you need to follow the dev setup for NextJS’ API layer. That will be in NextJS docs. The port will be the same as what your website’s port is
k
Hey @User , let me check with flask 0.12.2 and see if there is anything that can be done
10 Views