Hello everyone, does anybody encounter this error ``` {t: "2023-12-22T11:15:13.063Z", message: "midd...
k
Hello everyone, does anybody encounter this error
Copy code
{t: "2023-12-22T11:15:13.063Z", message: "middleware: Started", file: "/gateway/node_modules/supertokens-node/lib/build/supertokens.js:145:22" sdkVer: "16.6.5"}
2023-12-22T11:15:13.072Z com.supertokens {t: "2023-12-22T11:15:13.072Z", message: "middleware: Not handling because request path did not start with config path. Request path: /.well-known/jwks.json", file: "/gateway/node_modules/supertokens-node/lib/build/supertokens.js:152:26" sdkVer: "16.6.5"}
r
hey @khanprog
k
hello
r
can i see the supertokens.init on the backend?
k
sure
Copy code
supertokens.init({
  debug: true,
  framework: 'express',
  supertokens: {
    connectionURI: 'http://supertokens:3567'
    // apiKey: "", // TODO: Set an API key later on
  },
  appInfo: {
    appName: 'APP',
    apiDomain: 'http://localhost:3001',
    websiteDomain: 'http://localhost:3001',
    apiBasePath: '/auth',
    websiteBasePath: '/auth'
  },
  recipeList: [
    EmailPassword.init({
      signUpFeature: {
        formFields: [ // TODO: Update this to match the signup form
          {
            id: 'email'
          },
          {
            id: 'password'
          }
        ]
      }
    }),
    Session.init({
      cookieSecure: true
    }), // TODO: Update this section for proper handling
    Dashboard.init(), // TODO: see if we can add more things to the dashboard
    UserRoles.init()
  ]
})
r
right. So api base path is
/auth
. In nextjs, it should be
/api/auth
k
I am calling it from the middleware do I need to change this?
r
are you calling this endpoint manually?
k
I am using the SDK
import Session from 'supertokens-node/recipe/session';
r
@porcellus can help here.
k
I am using the pages router and basically used the biolerplate code you guys have on docs and try to make it work with this instead of the app router
r
we have a pages dir guide as well
k
yeah I went through that as well but to me the middleware approach seems more cleaner and efficient
r
in our guide, we set the apiBasePath to
/api/auth
k
thats true but that is what making use of the
/api
folder of nextjs. what if I want to use graphql for handling things, the thing is its working for signin and singup but not for this specific case where I put it in the middleware
p
hi. When exactly is this endpoint being called?
k
whenever someone access any page on the frontend the middleware will run
p
can you try to query
/auth/.well-known/jwks.json
on your backend?
k
Cannot GET /auth/.well-known/jwks.json
do I need to initialize the jwt recipe as well on the backend?
p
That shouldn't be necessary. Which node SDK version are you using?
r
this endpoint is on thje core
you need to query the core on
/.well-known/jwks.json
k
v20.0.9
r
not your next backend
k
okay
p
this is also exposed by the BE SDK.
r
the endpoint on the backend sdk is differenty
k
AppId or tenantId not found => Tenant with the following connectionURIDomain, appId and tenantId combination not found: (, public, auth)
r
@porcellus - it's
/auth/jwt/jwks.json
the endpoint on the core doens't have
/auth
part..
@khanprog you need to query
<core domain>/.well-known/jwks.json
p
oh right, my bad. I saw the openId discovery thing that starts with .well-known and though this was present as well.
k
Copy code
{
  "keys": [
    {
      "kty": "RSA",
      "kid": "d-1703142523611",
      "n": "ueyhzEB2kHdMixxi0V7rTkO64W08avpkSgZj7ltAkRrxYuV5gLBWDYcbUga3s1Ble76kLXS6xyjHUU0g8FvRC_g0AYrjllG-XoMU1CMCY8zrlULxM3S7yOmifUzZN3GmeCksnm7kNppj9MWFSAwC29VmekFJC0aPDp1pc4TNx3VKqvayrdF2pzlqqITQGJGQHquNC3vsky10ozXO0B168Fc76XYtDzF0aGFRMhuwwbEF5px-trdWryxHwUKi7tYD8OH-A-xVvKNBGjwXN_Uyote1ndD8AXLlES3oi-5_DBcrQZMJdXzCsxIE0njjxlBacldif2U8oTr3e8XrFGuXaw",
      "e": "AQAB",
      "alg": "RS256",
      "use": "sig"
    },
    {
      "kty": "RSA",
      "kid": "s-3e2e2f9a-e5c8-4498-9ab7-2bf8a5e8304e",
      "n": "pO40XRroIc7slSgoE3lxEJIxUiIt9WFdeKjd9oBEfuZIe24Jev_xCdhLWzV9Aa8eH4HLa1pqxwM7o4El4LHpzczZcrpyxVTN-CyZTE4axcxGp_Nxi41PvrPsUlQoJQ0OFxRpQRecauUr4v57agphF2GSzIREhZot6ldx5WSSJOqKYmWuoDCh7dredpgiLREnvUeXl58AdFlyjWswr_JC4l_RbWFwPfdto4-xGxjZd9SLioB83n4vyv7VLaX1j2Pns6OiB0Zt7sAW8E0bVlW2Yy34zt7Mu-aswWv2c0BB_VbMkbQIv-gh65qwDfkNIw91XQv_PAf6Olxy0R8YsaqW3w",
      "e": "AQAB",
      "alg": "RS256",
      "use": "sig"
    }
  ]
}
p
anyway, the issue is that something is querying this on your backend when it should be querying the core (or the version on your BE)
which is why I was asking when exactly is this endpoint getting called. does this error log pop up every time something goes through your middleware?
the output above seems correct.
k
yeah
r
@khanprog could you post your middleware code here? We need more details to help you
or upload your project to github
k
when I do the getSession method thats when this pops up
this is the middleware
Copy code
import { NextResponse } from 'next/server';
import { withSession } from 'utils/sessionUtils';
export function middleware(request) {
  if (
    request.nextUrl.pathname.startsWith('/admin/login') ||
    request.nextUrl.pathname.startsWith('/app/login')
  ) {
    return NextResponse.next();
  }
  if (request.headers.has('x-user-id')) {
    console.warn(
      'The FE tried to pass x-user-id, which is only supposed to be a backend internal header. Ignoring.',
    );
    request.headers.delete('x-user-id');
  }

  if (request.nextUrl.pathname.startsWith('/api/user')) {
    return NextResponse.next();
  }

  return withSession(request, async (session) => {
    console.log(
      '🚀 ~ file: middleware.js:16 ~ returnwithSession ~ session:',
      session,
    );
    if (session === undefined) {
      return NextResponse.redirect(new URL('/admin/login', request.url));
    }
    return NextResponse.next({
      headers: {
        'x-user-id': session.getUserId(),
      },
    });
  });
}

export const config = {
  matcher: ['/admin/:path*', '/app/:path*'],
};
r
the getSession function we have queries the core. Not the backend sdk
so not sure how the getSession would cause this
does
http://supertokens:3567
in your connection uri point to the core or to the next backend?
k
thats my undertanding as well
r
does getSession fail? Or succeed?
k
but maybe I am doing something wrong
Copy code
export async function getSSRSession(req, options = {}) {
  const query =
    req !== undefined
      ? Object.fromEntries(new URL(req.url).searchParams.entries())
      : {};
  const parsedCookies = Object.fromEntries(
    (req !== undefined ? req.cookies : cookies())
      .getAll()
      .map((cookie) => [cookie.name, cookie.value]),
  );
  let baseRequest = new PreParsedRequest({
    method: req !== undefined ? req.method : 'get',
    url: req !== undefined ? req.url : '',
    query: query,
    headers: req !== undefined ? req.headers : headers(),
    cookies: parsedCookies,
    getFormBody: () => req.formData(),
    getJSONBody: () => req.json(),
  });

  let baseResponse = new CollectingResponse();

  try {
    
    let session = await Session.getSession(baseRequest, baseResponse, options);
    return {
      session,
      hasInvalidClaims: false,
      hasToken: session !== undefined,
      baseResponse,
    };
  } catch (err) {
    console.log('🚀 ~ file: sessionUtils.js:47 ~ err:', err.message);

    if (Session.Error.isErrorFromSuperTokens(err)) {
      return {
        hasToken: err.type !== Session.Error.UNAUTHORISED,
        hasInvalidClaims: err.type === Session.Error.INVALID_CLAIMS,
        session: undefined,
        baseResponse,
        nextResponse: new NextResponse('Authentication required', {
          status: err.type === Session.Error.INVALID_CLAIMS ? 403 : 401,
        }),
      };
    } else {
      throw err;
    }
  }
}
if you check this code it will go to the catch block
r
no this seems fine
i just don't know why getSession is calling the nextjs backend instead of the core.
k
on frontend this is the backendConfig file I have
Copy code
import EmailPassword from 'supertokens-node/recipe/emailpassword'
import Session from 'supertokens-node/recipe/session'
import { appInfo } from './appInfo'
import SuperTokens from 'supertokens-node'

export const backendConfig = () => {
  return {
    framework: "express",
    supertokens: {
      connectionURI: "http://localhost:3001",
    },
    appInfo,
    recipeList: [
      EmailPassword.init(),
      Session.init(),
    ],
    isInServerlessEnv: false,
  }
}

let initialized = false
export function ensureSuperTokensInit() {
  if (!initialized) {
    SuperTokens.init(backendConfig())
    initialized = true
  }
}
r
huh?
you have just one backend config
and the connectionuri there too should point to the core.
k
I will try that in a sec
Thank you so much I just needed to change the port number for the session verification its working fine now
r
great!
27 Views