Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

Make API Post Request using Next.js and Koa Router (405 Method not allowed)

Make API Post Request using Next.js and Koa Router (405 Method not allowed)

AnswerBook
Shopify Partner
17 0 4

I used the Shopify CLI to create boilerplate app and handle the OAuth configuration, however, when it comes to documentation for using this with the Next.js API to setup your database, there is slim to no documentation. The only thing I really have to go off of is this example that uses Express and sqlite3.  According to the example, you create helper functions and place them in a directory, "helpers". However, you still make requests to that same file in the api directory? I have tried external examples with Mongoose (I am using MongoDB) calling directly to api/test.js and I still can't get them to work because of the same error.

 

server.js

 

  router.post("/api/add", async (ctx) => {
    try {
      /* Get the shop from the authorization header to prevent users from spoofing the data */
      shopDomain = await getShopUrlFromSession(ctx.req, ctx.res);
      if (shopDomain) {
        addTest(ctx.req, ctx.res);
      }
      res.status(201).send(response[0]);
    } catch (error) {
      res.status(500).send(error.message);
    }
  });
 
add.js (in "/helpers" directory)
 
import connectMongo from "../../../utils/connectMongo";
import { Shopify } from "@shopify/shopify-api";
import Test from "../../../models/testModel";
export default async function addTest(req, res) {
  try {
    console.log("CONNECTING TO MONGO");
    await connectMongo();
    console.log("CONNECTED TO MONGO");
    const session = await Shopify.Utils.loadCurrentSession(req, res, true);
    const client = new Shopify.Clients.Graphql(
      session.shop,
      session.accessToken
    );
    const shopId = `https://${session.shop}`;
    console.log("CREATING DOCUMENT");
    const test = await Test.create(req.body);
    console.log("CREATED DOCUMENT");
    res.json({ test });
  } catch (error) {
    console.log(error);
    res.json({ error });
  }
}
Reply 1 (1)

AnswerBook
Shopify Partner
17 0 4

As it turns out, the version of Shopify CLI I had was outdated. It spun up a Next.js app while the new app that is created from Shopify CLI does correspond to the example, hence some of my confusion. I'll have to decide on figuring out a way to make the API work with the Next.js app and Shopify auth/configuration or just update to the new one and utilize the example/tutorial with sqlite3.