#The getAccessToken method can only be used from the server side

59 messages · Page 1 of 1 (latest)

elder grove
#

I'm pretty new to NextJS stuff, mostly a back end dev. My GraphQL back end uses Auth0, I just need the access token from the logged in session to pass into the fetch for my GraphQL queries but am getting this error. Any ideas?

#

My login is all functional, GraphQL stuff is all functional, just something in between here that I am missing I think

#

I feel like this is way more difficult than it needs to be :\

whole zenith
#

how does pages/api/graphQL.tsx look like?

elder grove
#
import { getAccessToken } from "@auth0/nextjs-auth0";
// GraphQL Fetch

const graphQL = async (req:any, res:any) => {
  const { operationsDoc, variables } = req.body;
  const { accessToken } = await getAccessToken(req, res, {
    scopes: ["openid", "profile", "email"],
  });
  const operationType = operationsDoc.match(/(mutation|query)\s/)![1];
  const operationName = (operationType == "mutation") ? operationsDoc.match(/mutation\s+(\w+)/)![1] : operationsDoc.match(/query\s+(\w+)/)![1];
  const result = await fetch((process.env.AUTH0_AUDIENCE) ? process.env.AUTH0_AUDIENCE : "", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${accessToken}`
        },
        body: JSON.stringify({
          query: operationsDoc,
          variables: variables,
          operationName: operationName
        })
      }
    );
    const data = await result.json();
    return data;
};
export default graphQL;```
whole zenith
#

you shouldn't import react here

elder grove
#

ah ok, took that out

#

still getting that error though 😦

elder grove
#

I have that set in my [...auth0].js

#

I think I am just accessing this incorrectly but I am doing it exactly as they said to in their docs

whole zenith
#

one sec let me try

#

seem like no problem on my side

elder grove
#

doesn't seem to matter what I do

#

i keep getting this

whole zenith
#

I can run it

elder grove
whole zenith
#

maybe you have something cause nextjs-auth0 think its running in browser

#

try create a new project and run the code

elder grove
#

kk I'll give it a shot, ty

#

I think I am just calling on this thing wrong.. I am submitting a form which goes to a function to parse the form data, then post it to the GraphQL API

whole zenith
#

as long as the getAccessToken function is running in /api/**/* is fine

elder grove
#

submitForm is at /pages/api/submitForm.tsx, graphQL is at /pages/api/graphQL.tsx

whole zenith
#

is submitForm a page or a component?

#

or an api?

elder grove
#

Suppose a page, doesn't need to be though

#

I could just have it push to a different page when it finishes

whole zenith
#

if its a page, you should place it in pages/submitForm.tsx

elder grove
#
import graphQL from '../pages/api/graphQL';
import { Typography } from '@mui/material';

const submitForm = async (req: any, res: any) => {
  req.preventDefault();
  const data = new FormData(req.currentTarget);
  var formData: any = {};
  data.forEach((value, key) => {
    formData[key] = value;
  });
  for(var key in req.currentTarget.elements) {
    if(formData[req.currentTarget.elements[key].id] == undefined && req.currentTarget.elements[key].value != null && req.currentTarget.elements[key].value != "" && req.currentTarget.elements[key].value != undefined && req.currentTarget.elements[key].id != undefined && req.currentTarget.elements[key].id != "") {
      if(req.currentTarget.elements[key].type == "checkbox") {
        formData[req.currentTarget.elements[key].id] = req.currentTarget.elements[key].checked;
      } else {
        formData[req.currentTarget.elements[key].id] = req.currentTarget.elements[key].value;
      }
    }
  }
  for(var key in formData) {
    if(formData[key] != undefined && formData[key] != null && formData[key] != "") {
      const query = `
        mutation FormData($Endpoint: String = "", $Key: String = "", $Val: String = "") {
          insert_WD_FormData(objects: {Endpoint: $Endpoint, Key: $Key, Val: $Val}) {
            affected_rows
          }
        }
      `;
      const variables = {
        Endpoint: Router.asPath,
        Key: key,
        Val: formData[key]
      };
      req.body = {
        operationsDoc: query,
        variables: variables
      }
      const { data, error } = await graphQL(req, res);
      
      if (error) return <div>Failed to load</div>;
      if (!data) return <div>Loading...</div>;
      return <Typography>{JSON.stringify(data)}</Typography>;
      //Router.push(Router.asPath + '/submitted');
    }
  } 
};

export default submitForm;```
whole zenith
#

you can't import graphQL function and run directly here

elder grove
#

suboptimal way to do this thing, I know lol

whole zenith
#

where do you use submitForm?

#

you should do a fetch when the form is submitted

elder grove
#

<form onSubmit={submitForm} id="onboarding">

whole zenith
#
   fetch("/api/graphQL", {
      body: JSON.stringify({operationsDoc: '', variables:''}),
      headers: {
        'content-type': 'application/json'
      }
    })
#

change graphQL(req, res) to fetch

#

that's why it is saying you are running in browser lol

#

you need to use post with body

    fetch("/api/graphQL", {
      method: 'POST',
      body: JSON.stringify({operationsDoc: query, variables }),
      headers: {
        'content-type': 'application/json'
      }
    })
elder grove
#

hmm

#

still not getting anything

whole zenith
#

then modify your graphQL to this

import { getAccessToken } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";
// GraphQL Fetch

const graphQL = async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method !== "POST") {
    return res.status(500).send("Method not allowed");
  }

  const { operationsDoc, variables } = req.body;
  const { accessToken } = await getAccessToken(req, res, {
    scopes: ["openid", "profile", "email"],
  });

  const operationType = operationsDoc.match(/(mutation|query)\s/)![1];
  const operationName =
    operationType == "mutation"
      ? operationsDoc.match(/mutation\s+(\w+)/)![1]
      : operationsDoc.match(/query\s+(\w+)/)![1];
  const result = await fetch(
    process.env.AUTH0_AUDIENCE ? process.env.AUTH0_AUDIENCE : "",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
      },
      body: JSON.stringify({
        query: operationsDoc,
        variables: variables,
        operationName: operationName,
      }),
    }
  );
  const data = await result.json();
  return res.json(data);
};

export default graphQL;
#

you need res.json(data) not just return data

#

and i added the type for req and res

#

also, you should move submitForm file to other place. everything in /pages will be a route in nextjs

elder grove
#

moved submit to components

#

ty also, I am still going through this and trying it out

whole zenith
#

should work now I think 😉

elder grove
#

Not getting an error but it isn't making its way to the GraphQL server I think

whole zenith
#

console.log(data)

elder grove
#

{
errors: [
{
extensions: [Object],
message: 'Could not verify JWT: JWSError (CompactDecodeError Invalid number of parts: Expected 3 parts; got 5)'
}
]
}

whole zenith
#

not sure what is that

elder grove
#

I can dig on that one, thank you very very much for all of your help

whole zenith
#

should be something wrong with the token