nuxt-auth
nuxt-auth copied to clipboard
Local Provider : baseURL not considered after deployment
Environment
- Operating System: Windows_NT
- Node Version: v16.18.0
- Nuxt Version: 3.4.3
- Nitro Version: 2.3.3
- Package Manager: [email protected]
- Builder: vite
- User Config: runtimeConfig, css, typescript, build, modules, app, piniaPersistedstate, pwa, auth
- Runtime Modules: @kevinmarrec/[email protected], @pinia/[email protected], @pinia-plugin-persistedstate/[email protected], @sidebase/[email protected], ()
- Build Modules: -
Reproduction
No response
Describe the bug
Good morning, I use the "Local" Provider without any problem on my laptop with an API back-end on http://localhost:8080
But when I deploy my app on my Web server, the baseUrl parameter does not seem to be taken into account.
Here is my conf:
.env (laptop)
PORT=3000
NITRO_PORT=3000
NUXT_PUBLIC_URL_FRONT=http://localhost:3000/
NUXT_PUBLIC_URL_API=http://localhost:8080/
nuxt.config.ts:
auth: {
baseURL: process.env.NUXT_PUBLIC_URL_API,
provider: {
type: "local",
endpoints: {
signIn: { path: "auth/login", method: "post" },
signOut: { path: "auth/logout", method: "post" },
signUp: { path: "auth/register", method: "post" },
getSession: { path: "auth/profile", method: "get" },
},
pages: {
login: "/login",
},
token: {
signInResponseTokenPointer: "/token/accessToken",
},
},
globalAppMiddleware: {
isEnabled: false,
},
},
When I display the contents of the conf variable I have this: On my Laptop :
{
"public": {
"urlFront": "http://localhost:3000/",
"urlApi": "http://localhost:8080/",
...
"auth": {
"computed": {
"origin": "http://localhost:8080",
"pathname": "/",
"fullBaseUrl": "http://localhost:8080"
},
"isEnabled": true,
"session": {
"enableRefreshPeriodically": false,
"enableRefreshOnWindowFocus": true
},
"globalAppMiddleware": {
"isEnabled": false,
"allow404WithoutAuth": true,
"addDefaultCallbackUrl": true
},
"baseURL": "http://localhost:8080/",
"provider": {
"type": "local",
"pages": {
"login": "/login"
},
"endpoints": {
"signIn": {
"path": "auth/login",
"method": "post"
},
"signOut": {
"path": "auth/logout",
"method": "post"
},
"signUp": {
"path": "auth/register",
"method": "post"
},
"getSession": {
"path": "auth/profile",
"method": "get"
}
},
"token": {
"signInResponseTokenPointer": "/token/accessToken",
"type": "Bearer",
"headerName": "Authorization",
"maxAgeInSeconds": 1800
}
}
}
},
on the web server :
{
"public": {
"urlFront": "https://dev.website.org/",
"urlApi": "https://dev.api.website.org/",
...
"auth": {
"computed": {
"origin": "",
"pathname": "/api/auth",
"fullBaseUrl": "/api/auth"
},
"isEnabled": true,
"session": {
"enableRefreshPeriodically": false,
"enableRefreshOnWindowFocus": true
},
"globalAppMiddleware": {
"isEnabled": false,
"allow404WithoutAuth": true,
"addDefaultCallbackUrl": true
},
"provider": {
"type": "local",
"pages": {
"login": "/login"
},
"endpoints": {
"signIn": {
"path": "auth/login",
"method": "post"
},
"signOut": {
"path": "auth/logout",
"method": "post"
},
"signUp": {
"path": "auth/register",
"method": "post"
},
"getSession": {
"path": "auth/profile",
"method": "get"
}
},
"token": {
"signInResponseTokenPointer": "/token/accessToken",
"type": "Bearer",
"headerName": "Authorization",
"maxAgeInSeconds": 1800
}
}
}
},
However the NUXT_PUBLIC_URL_API constant is well loaded by Nuxt as shown by the public / urlApi variable of the Nuxt config
And suddenly, as the baseUrl variable is not configured, when I call signIn, the http post call is made on:
"https://dev.website.org/api/auth/auth/login"
instead of :
"https://dev.api.website.org/auth/login"
Additional context
No response
Logs
No response
and here is the pm2 config on my web server :
"apps": [
{
"name": "dev.website.org",
"exec_mode": "fork",
"port": "3002",
"script": "NUXT_PUBLIC_ENVIRONNEMENT=dev NUXT_ENVIRONNEMENT=dev PORT=3002 NITRO_PORT=3002 NUXT_PUBLIC_URL_FRONT=https://dev.website.org/ NUXT_PUBLIC_URL_API=https://dev.api.website.org/ node .output/server/index.mjs",
"cwd": "/var/www/dev.website.org",
"autorestart": true,
"watch": false,
"max_memory_restart": "1G",
"env": {
"NODE_ENV": "development"
},
"env_production": {
"NODE_ENV": "production"
}
}
Any idea ? Has someone used the local provider with basePath in production ?
IT works only if the baseUrl is hardcoded like that in nuxt.config.ts :
auth: {
baseURL: "https://dev.api.website.org/",
provider: {
type: "local",
....
},
~~Regarding your issue: It seems like there is no baseURL
config field according to the docs.~~ Just noticed that you're using version 0.6.0 where this has changed
I'm currently encountering the same issue in my OAuth flow.
My config:
auth: {
origin: process.env.AUTH_ORIGIN,
basePath: '/api/auth',
defaultProvider: 'foobar',
enableGlobalAppMiddleware: false,
},
I've checked that the AUTH_ORIGIN
is correctly set to stage.example.com
.
This is the OAuth flow observed from the Devtools:
- GET
https://stage.example.com/api/auth/signin?callbackUrl=https://stage.example.com/
- Got redirect response to
/login?callbackUrl=http://localhost:3000&error=undefined
- Redirected to my Backend
https://stage.example.com/oauth/authorize?client_id=...&scope=&response_type=code&redirect_uri=http://localhost:3000/api/auth/callback/foobar&state=...
I have no idea why the redirect response includes a callbck URL to localhost:3000
, there is no such environment value or config setting. I can only imagine that this value is taken from the currently running host/port.
Yeah, we do deduce some stuff automatically - but in 0.6 this is a bit broken at the moment, sorry for that - the beta is not quite stable.
I don't have super much time at the moment but will try to resolve this ASAP!
@kaboume as a workaround you could try setting the NEXTAUTH_URL
env variable. This seems to work fine for me
thanks @romanzipp
It's better but I'v still an issue.
Now the Call Api made by SignIn meythod is https://dev.api.website.org/api/auth/auth/login in the place of https://dev.api.website.org/auth/login
So Nuxt Auth added /ai/auth
When I display the config :
auth : { computed : {origin: '', pathname: '/api/auth', fullBaseUrl: '/api/auth'}
~Regarding your issue: It seems like there is no
baseURL
config field according to the docs.~ Just noticed that you're using version 0.6.0 where this has changedI'm currently encountering the same issue in my OAuth flow.
My config:
auth: { origin: process.env.AUTH_ORIGIN, basePath: '/api/auth', defaultProvider: 'foobar', enableGlobalAppMiddleware: false, },
I've checked that the
AUTH_ORIGIN
is correctly set tostage.example.com
.This is the OAuth flow observed from the Devtools:
- GET
https://stage.example.com/api/auth/signin?callbackUrl=https://stage.example.com/
- Got redirect response to
/login?callbackUrl=http://localhost:3000&error=undefined
- Redirected to my Backend
https://stage.example.com/oauth/authorize?client_id=...&scope=&response_type=code&redirect_uri=http://localhost:3000/api/auth/callback/foobar&state=...
I have no idea why the redirect response includes a callbck URL to
localhost:3000
, there is no such environment value or config setting. I can only imagine that this value is taken from the currently running host/port.
having the same issue
I had the same issue but i was able to fix it by adding:
computed: {
origin: true,
fullBaseUrl: process.env.AUTH_URL,
},
to
auth:{}
I had the same issue but i was able to fix it by adding:
computed: { origin: true, fullBaseUrl: process.env.AUTH_URL, },
to
auth:{}
Sorry, can I know where did you add this code? I mean changing from
computed: {
origin: true,
fullBaseUrl: process.env.AUTH_URL,
},
to
auth:{}
@BracketJohn : is this issue fixed with the 0.6.0-beta.3 release ?
I had the same issue but i was able to fix it by adding:
computed: { origin: true, fullBaseUrl: process.env.AUTH_URL, },
to
auth:{}
Sorry, can I know where did you add this code? I mean changing from
computed: { origin: true, fullBaseUrl: process.env.AUTH_URL, },
to
auth:{}
i added the whole computed object inside the auth object like this:
auth: {
computed: {
origin: true,
fullBaseUrl: process.env.AUTH_URL,
},
...
}
Good morning, I see that the bug has still not been fixed by the team. I wonder if the project is still well maintained?
Hi @kaboume,
We have been pretty swampped over the summer with other projects, which is why our focus sadly had to shift away from sidebase for a while. I am currently rammping up my work on the project again and have this on my list of hotfixes, to look into!
Hello @kaboume @romanzipp 👋
I did some testing myself on version 0.6.0-beta.7. I can report the following:
- setting
baseURL
tohttp://localhost:3001/api/users
modified all the requests properly and gave me the callback url of:
https://github.com/login/oauth/authorizeredirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fapi%2Fusers%2Fcallback%2Fgithub
Which did take my new route into account. Therefore, I conclude that in my Dev setup the baseURL
property is working correctly.
According to the code, this should also be the case, as we take the given baseURL
and pharse it for the origin as well as the path
here using this package: https://github.com/unjs/ufo#parseurl
My follow up questions to properly determine your issues:
- What versions are you using. Does it still happen on
0.6.0-beta.7
? - Is this an issue only happening on production or already on dev servers?
- Does this only happen if you inject environment variables, or also when hard setting the value (I think this was mentioned above)
- Do you use the same properties I used below (if using >
0.6.0
)
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@sidebase/nuxt-auth'],
devServer: {
port: 3001
},
auth: {
baseURL: 'http://localhost:3001/api/users',
provider: {
type: 'authjs'
},
globalAppMiddleware: {
isEnabled: true
}
}
})
Hi @zoey-kaiser I just tested with version 0.6.0-beta.7 and I encounter the same problem. When I develop locally, no problem. The problem appears when I deploy on a server (npm run build...)
Here is my configuration:
auth: {
baseURL: process.env.NEXTAUTH_URL,
provider: {
type: "local",
endpoints: {
signIn: { path: "auth/login", method: "post" },
signOut: { path: "auth/logout", method: "post" },
signUp: { path: "auth/register", method: "post" },
getSession: { path: "auth/profile", method: "get" },
},
pages: {
login: "/login",
},
token: {
signInResponseTokenPointer: "/token/accessToken",
},
},
My frontend calls my nodeJs backend to authenticate users with a login/password. Thank you for your help.
Hi @kaboume,
Could you be so kind to tell me a bit about your deployment? Is it only a normal webserver where you then start the application or are you using Vercel, Netlify etc. Also, does this happen when you build locally and start for production or only on your actual webserver?
Closed due to inactivity. If you still require more help, please comment in this issue and we can reopen it!
This issue still persists and not even after deployment, but locally too.
This is my auth
config. NUXT_PUBLIC_API_BASE
is set to http://localhost:3333
auth: {
baseURL: process.env.NUXT_PUBLIC_API_BASE || "http://localhost:3333",
provider: {
type: "local",
endpoints: {
signIn: { path: "/login", method: "post" },
signOut: { path: "/logout", method: "post" },
signUp: { path: "/register", method: "post" },
getSession: { path: "/session", method: "get" },
},
pages: {
login: "/auth/login",
},
token: { signInResponseTokenPointer: "/accessToken" },
sessionDataType: {},
},
enableSessionRefreshPeriodically: 5000,
enableSessionRefreshOnWindowFocus: true,
globalMiddlewareOptions: {
allow404WithoutAuth: true, // Defines if the 404 page will be accessible while unauthenticated
addDefaultCallbackUrl: "/", // Where authenticated user will be redirected to by default
},
},
Using signIn
method and it uses this URL for request http://localhost:3333/api/auth/login
Found out that these lines are probably the fault here
https://github.com/sidebase/nuxt-auth/blob/main/src/module.ts#L111-L113
And baseURL
works when you put trailing slash at the end; like so http://localhost:3333/
, which shouldn't work like so. It should work without trailing slash.
Found out that these lines are probably the fault here
And
baseURL
works when you put trailing slash at the end; like sohttp://localhost:3333/
, which shouldn't work like so. It should work without trailing slash.
Glad I found this issue and scrolled down. I wanted to report this issue aswell. I documented this in my config like so:
// IMPORTANT: it needs a trailing slash else /api/auth is appended
// but the trailing slash is not set for the endpoints
baseURL: `${process.env.API_URL}/` || 'https://api.domain.test/',
So I think this might be related, although it probably is because of this line: https://github.com/sidebase/nuxt-auth/blob/5d713aa419bcefc342f6a6e14899db6cc3d05d7f/src/module.ts#L122
And baseURL works when you put trailing slash at the end; like so http://localhost:3333/, which shouldn't work like so. It should work without trailing slash.
Thanks for finding this. I am not sure if this is a bug, to me it looks like an intended feature because of the default /api/auth
pathname:
https://github.com/sidebase/nuxt-auth/blob/5d713aa419bcefc342f6a6e14899db6cc3d05d7f/src/module.ts#L111
Modifying this will be a hard breaking change for our users who already use no trailing slash at the end.
We already use AUTH_ORIGIN
for authjs
provider, maybe it makes sense to unify approaches. I would think about it.
True, it is breaking change. I see that. But it should not append /api/auth
when a variable is set in the config, this is weird behaviour in my opinion. It should only default to /api/auth
and not treat the baseURL as a prefix to /api/auth
. The endpoints config in the provider settings is where you set the /api/auth
or whatever is needed.
I started a new project with the 0.7.2 nuxt auth release and the problem is always here.
My nuxt.config.js file :
auth: {
baseURL: process.env.BASE_URL,
provider: {
type: "local",
endpoints: {
signIn: { path: "/auth/login", method: "post" },
signOut: false,
signUp: { path: "auth/register", method: "post" },
getSession: { path: "auth/user", method: "get" },
},
token: { signInResponseTokenPointer: "/tokens/access/token" },
},
},
my .gitlab-ci.yml file :
job:deploy_dev:
stage: stagedev
only:
- develop
script:
- npm install
- npm run build
- echo "$DEV_SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan -H [IP] >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
- rsync -rpl -e "ssh " --exclude='.git/' --exclude='.gitlab-ci.yml' ./ [XXX}:[XXX]
- ssh [XXX] "pm2 restart [XXX]pm2.json --only myapp --update-env"
my pm2.json file :
{
"apps": [
{
"name": "myapp",
"exec_mode": "fork",
"port": "3012",
"script": ".output/server/index.mjs",
"env": {
"NODE_ENV": "development",
"PORT": 3012,
"NITRO_PORT": 3012,
"BASE_URL": "https://backend.com/v1/",
"AUTH_ORIGIN": "https://backend.com/v1/",
"NEXTAUTH_URL": "https://backend.com/v1/"
},
"env_production": {
"NODE_ENV": "production"
}
},
The signIn() method calls https://[frontend]/api/auth/auth/login instead of https://backend.com/v1/auth/login
I specify that locally, it works well, it is just when I deploy on the server that it does not work
I got the same problem, after upgrading to the newest version.
In the file https://github.com/sidebase/nuxt-auth/blob/main/src/runtime/composables/local/useAuth.ts#L22 it just uses:
const runtimeConfig = await callWithNuxt(nuxt, useRuntimeConfig)
const config = useTypedBackendConfig(runtimeConfig, 'local')
const { path, method } = config.endpoints.signIn
const response = await _fetch<Record<string, any>>(nuxt, path, {
method,
body: credentials,
params: signInParams ?? {}
})
where path
is just /auth/login
... it should also consider the basePath option.
For instance if basePath is set with: "http://localhost:8000" it should send the login request to:
http://localhost:8000/auth/login
Okay I fixed it by removing the trailing slashes in the endpoints config:
endpoints: {
signIn: { path: "auth/login", method: "post" },
getSession: { path: "auth/user", method: "get" },
},
And my comment before is not valid, it considers the basePath
Okay I fixed it by removing the trailing slashes in the endpoints config:
endpoints: { signIn: { path: "auth/login", method: "post" }, getSession: { path: "auth/user", method: "get" }, },
And my comment before is not valid, it considers the basePath
No working for me, this is my config. I'm using an external backend API
auth: {
provider: {
baseURL: 'https://url_backend.test/',
type: 'refresh',
endpoints: {
signIn: { path: 'login', method: 'post' },
signOut: { path: 'logout', method: 'post' },
signUp: false,
getSession: { path: 'me', method: 'get' },
refresh: { path: 'refresh', method: 'post' },
},
token: {
signInResponseTokenPointer: 'data/access_token',
cookieName: 'access_token',
type: 'Bearer',
maxAgeInSeconds: 60 * 60,
sameSiteAttribute: 'strict',
},
refreshOnlyToken: false,
refreshToken: {
signInResponseRefreshTokenPointer: 'data/access_token',
cookieName: 'access_token',
refreshRequestTokenPointer: 'access_token',
maxAgeInSeconds: 20160 * 60,
},
pages: {
login: '/login',
},
},
},
Okay I fixed it by removing the trailing slashes in the endpoints config:
endpoints: { signIn: { path: "auth/login", method: "post" }, getSession: { path: "auth/user", method: "get" }, },
And my comment before is not valid, it considers the basePath
Doesn't work for me !
@kaboume, please have a look at the updated documentation, where we provided some more direct instructions for using external backends: https://auth.sidebase.io/guide/local/quick-start#using-an-external-backend
Also feel free to add your suggestions to #797, where we are discussing on improving this behaviour.
I think this issue is not related to any specific bugs and comes more from misconceptions brought about by outdated and wrong documentation. I will close this issue for now. Please retry your setups with the new documentation and if you experience any bugs, please open a new issue. This is primarily for housekeeping reasons and to ensure we have a better overview of issues and can track down what is going on 😊
ok, I finally understood where the problem was coming from. the environment variable is taken into account at the time of the "npm run build" and not at the time of running pm2 on the server!
So, here is .gitlab-ci.yml file updated :
job:deploy_dev:
stage: stagedev
only:
- develop
script:
- chmod +x ./setup_env_dev.sh
- ./setup_env_dev.sh
- npm install
- npm run build
- echo "$DEV_SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
- ssh-keyscan -H [IP] >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
- echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
- rsync -rpl -e "ssh " --exclude='.git/' --exclude='.gitlab-ci.yml' ./ [XXX}:[XXX]
- ssh [XXX] "pm2 restart [XXX]pm2.json --only myapp --update-env"
And the neaw file: setup_env_dev.sh
#!/bin/bash
echo "BASE_URL="$DEV_BASE_URL > .env
cat .env