Problem generating discount code

Topic summary

Un desarrollador está intentando implementar un sistema de códigos de descuento en su sitio web usando Next.js 14 con app router y llamadas directas a la API de Shopify mediante fetch.

Problema principal:
Recibe el error: “DiscountCodeBasicInput isn’t a defined input type (on $basicCodeDiscount)”

Contexto importante:

  • La misma consulta funciona perfectamente en GraphiQL dentro de Shopify
  • La conexión a Shopify está correcta (puede recuperar productos, usar el carrito y otras funciones)
  • Esto descarta problemas de conexión o autenticación

Código compartido:
El desarrollador proporcionó su función createDiscountCode() que:

  • Genera códigos únicos
  • Llama a shopifyFetch con la mutación createDiscountCodeMutation
  • Incluye variables para configurar descuentos (porcentaje, fechas, selección de clientes)
  • Maneja errores de userErrors

También compartió su función shopifyFetch personalizada que maneja las peticiones POST a Shopify.

Estado: La discusión permanece abierta sin respuestas ni solución. El error sugiere un posible problema con la definición del tipo de input en la mutación GraphQL o incompatibilidad de versiones de la API.

Summarized with AI on November 5. AI used: claude-sonnet-4-5-20250929.

I’m trying to implement a system on my website where I can create discount codes. I’m using Next.js 14 with the app router, and I’m making direct API calls via fetch. I followed the example from the documentation, but I keep encountering the same issue:

“DiscountCodeBasicInput isn’t a defined input type (on $basicCodeDiscount)”

I’ve also tried using GraphiQL within Shopify, and it works perfectly there, so I don’t think it’s a connection problem. My connection to Shopify is correct since I’m able to retrieve products, use the cart, and perform other functions without any issues. Has anyone seen this error before, or can offer some guidance?

This is my function that calls Shopify Fetch and provides the variables.

export async function createDiscountCode(
  email: string
): Promise<{ success: boolean; code?: string; error?: string }> {
  const code = generateUniqueCode();
  try {
    const res = await shopifyFetch<ShopifyCreateDiscountCodeOperation>({
      query: createDiscountCodeMutation,
      variables: {
        basicCodeDiscount: {
          title: "20% off all items during the summer of 2022",
          code: code,
          startsAt: "2022-06-21T00:00:00Z",
          endsAt: "2022-09-21T00:00:00Z",
          customerSelection: {
            all: true
          },
          customerGets: {
            value: {
              percentage: 0.2
            },
            items: {
              all: true
            }
          },
          appliesOncePerCustomer: true
        }        
      },
      cache: 'no-store'
    });

    if (res.body.data.discountCodeBasicCreate.userErrors.length > 0) {
      throw new Error(res.body.data.discountCodeBasicCreate.userErrors[0]!.message);
    }

    const createdCode =
      res.body.data.discountCodeBasicCreate.codeDiscountNode.codeDiscount.codes.edges[0]!.node;

    return { success: true, code: createdCode };
  } catch (error) {
    console.error('Error creating discount code:', error);
    return { success: false, error: 'Failed to create discount code' };
  }
}

and the shopifyFetch function:

export async function shopifyFetch<T>({
  cache = 'force-cache',
  headers,
  query,
  tags,
  variables
}: {
  cache?: RequestCache;
  headers?: HeadersInit;
  query: string;
  tags?: string[];
  variables?: ExtractVariables<T>;
}): Promise<{ status: number; body: T } | never> {
  try {
    const result = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Storefront-Access-Token': key,
        ...headers
      },
      body: JSON.stringify({
        ...(query && { query }),
        ...(variables && { variables })
      }),
      cache,
      ...(tags && { next: { tags } })
    });

    const body = await result.json();

    if (body.errors) {
      throw body.errors[0];
    }

    return {
      status: result.status,
      body
    };
  } catch (e) {
    if (isShopifyError(e)) {
      throw {
        cause: e.cause?.toString() || 'unknown',
        status: e.status || 500,
        message: e.message,
        query
      };
    }

    throw {
      error: e,
      query
    };
  }
}

and finally the query:

export const createDiscountCodeMutation = `
  mutation discountCodeBasicCreate($basicCodeDiscount: DiscountCodeBasicInput!) {
  discountCodeBasicCreate(basicCodeDiscount: $basicCodeDiscount) {
    codeDiscountNode {
      codeDiscount {
        ... on DiscountCodeBasic {
          title
          codes(first: 10) {
            nodes {
              code
            }
          }
          startsAt
          endsAt
          customerSelection {
            ... on DiscountCustomerAll {
              allCustomers
            }
          }
          customerGets {
            value {
              ... on DiscountPercentage {
                percentage
              }
            }
            items {
              ... on AllDiscountItems {
                allItems
              }
            }
          }
          appliesOncePerCustomer
        }
      }
    }
    userErrors {
      field
      code
      message
    }
  }
}
`;