#Can't deploy next app

53 messages · Page 1 of 1 (latest)

full obsidian
#

So i have this project: https://github.com/Felopater-Melika/Astral-Store

I am trying to deploy it but i think there is a problem in the page.tsx
i get this error:

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6498:19)
    at successSteps (node:internal/deps/undici/undici:6472:27)
    at node:internal/deps/undici/undici:1145:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:204:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6498:19)
    at successSteps (node:internal/deps/undici/undici:6472:27)
    at node:internal/deps/undici/undici:1145:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:204:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
- info Generating static pages (4/4)
> Export encountered errors on following paths:
    /page: /
 ELIFECYCLE  Command failed with exit code 1.
Error: Command "pnpm run build" exited with 1
BUILD_UTILS_SPAWN_1: Command "pnpm run build" exited with 1
GitHub

Contribute to Felopater-Melika/Astral-Store development by creating an account on GitHub.

iron walrusBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
full obsidian
#

here is the log of build on my device:

> [email protected] build C:\Users\philo\projects\Astral-Store
> next build

- info Loaded env from C:\Users\philo\projects\Astral-Store\.env.local
- info Creating an optimized production build
- info Compiled successfully
- info Linting and checking validity of types
- info Collecting page data
- info Generating static pages (4/4)
- info Finalizing page optimization

Route (app)                                Size     First Load JS
┌ ○ /                                      0 B                0 B
└ ○ /api/items                             0 B                0 B
+ First Load JS shared by all              85.9 kB
  ├ chunks/106-d4a3cb813406ce7d.js         25.3 kB
  ├ chunks/58b30e71-cd52d4eb5faa369d.js    50.5 kB
  ├ chunks/798-41b1d96d0c1cde1a.js         8.19 kB
  ├ chunks/main-app-bbe35e5a4bef5747.js    215 B
  └ chunks/webpack-cf3820b6dd6f5e92.js     1.74 kB

Route (pages)                              Size     First Load JS
─ ○ /404                                   182 B          74.9 kB
+ First Load JS shared by all              74.7 kB
  ├ chunks/framework-510ec8ffd65e1d01.js   45 kB
  ├ chunks/main-a5126d5d6f29e0b5.js        27.7 kB
  ├ chunks/pages/_app-cb21f3cd47a92abc.js  194 B
  └ chunks/webpack-cf3820b6dd6f5e92.js     1.74 kB

○  (Static)  automatically rendered as static HTML (uses no initial props)
twin meteor
full obsidian
#

everything is also working fine in development too

twin meteor
full obsidian
#

😂

twin meteor
#

is the api route also nextjs?

full obsidian
#

yes

twin meteor
#

so the page is calling back to /api?

full obsidian
#

it's basically extracting the logic of fetching products from shopify

full obsidian
twin meteor
#

is the page a client component?

full obsidian
#

const response = await fetch(
${ process.env.VERCEL_URL ? process.env.VERCEL_URL : 'http://localhost:3000' }/api/items,
{ next: { revalidate: 20 } }
);

full obsidian
twin meteor
#

so there are multiple issues there

full obsidian
#

but i just changed it to client just to see if it being server component is the issue and still got this

TypeError: Failed to parse URL from astral-store-philo-l826er2r1-felopater-melika.vercel.app/api/items
    at new Request (node:internal/deps/undici/undici:7004:19)
    at r (/vercel/path0/.next/server/chunks/950.js:46244:65)
    at doOriginalFetch (/vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:273:24)
    at /vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:392:20 {
  [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
      at new NodeError (node:internal/errors:399:5)
      at URL.onParseError (node:internal/url:566:9)
      at new URL (node:internal/url:646:5)
      at new Request (node:internal/deps/undici/undici:7002:25)
      at r (/vercel/path0/.next/server/chunks/950.js:46244:65)
      at doOriginalFetch (/vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:273:24)
      at /vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:392:20 {
    input: 'astral-store-philo-l826er2r1-felopater-melika.vercel.app/api/items',
    code: 'ERR_INVALID_URL'
  }
}
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Failed to parse URL from astral-store-philo-l826er2r1-felopater-melika.vercel.app/api/items
    at new Request (node:internal/deps/undici/undici:7004:19)
    at r (/vercel/path0/.next/server/chunks/950.js:46244:65)
    at doOriginalFetch (/vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:273:24)
    at /vercel/path0/node_modules/next/dist/server/lib/patch-fetch.js:392:20
- info Generating static pages (4/4)
> Export encountered errors on following paths:
    /page: /
 ELIFECYCLE  Command failed with exit code 1.
Error: Command "pnpm run build" exited with 1
BUILD_UTILS_SPAWN_1: Command "pnpm run build" exited with 1
twin meteor
#
  1. you dont need hostname for fetch
#
  1. server components dont need to call api
#

its already on the server

#

does that make sense?

full obsidian
#

yeah i am just extracting the logic i guess

#

because it's a gql request and i have to use the fetch function instead of graphql request

#
import { NextResponse } from 'next/server';
import { gql, request } from 'graphql-request';

const getProducts = async (): Promise<any> => {
  const url = `https://${process.env.STORE_NAME}.myshopify.com/api/2023-04/graphql.json`;
  const headers = {
    'X-Shopify-Storefront-Access-Token': process.env
      .X_SHOPIFY_ACCESS_TOKEN as string,
  };

  const query = gql`
    query ProductsQuery {
      collections(
        first: 3
        query: "title:solars OR title:galaxies OR title:planets"
      ) {
        edges {
          node {
            title
            products(first: 10) {
              edges {
                node {
                  id
                  title
                  description
                  variants(first: 1) {
                    edges {
                      node {
                        price {
                          amount
                        }
                      }
                    }
                  }
                  images(first: 1) {
                    edges {
                      node {
                        url
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  `;

  return await request(url, query, undefined, headers);
};

export async function GET() {
  try {
    const { collections } = await getProducts();

    const solars = collections.edges
      .find(({ node }: any) => node.title.toLowerCase() === 'solars')
      .node.products.edges.map(({ node }: any) => node);

    const galaxies = collections.edges
      .find(({ node }: any) => node.title.toLowerCase() === 'galaxies')
      .node.products.edges.map(({ node }: any) => node);

    const planets = collections.edges
      .find(({ node }: any) => node.title.toLowerCase() === 'planets')
      .node.products.edges.map(({ node }: any) => node);
    return NextResponse.json({
      products: {```
#

        solars,
        galaxies,
        planets,
      },
    });
  } catch (error) {
    console.error(error);
    NextResponse.json({ error: 'Failed to fetch products.tsx' });
  }
}
twin meteor
#

if you are calling for data from a client component, yes you need host and yes you can call /api. If its a server component you should be getting the data directly

#

do you plan to call the api route from things other than the app itself?

full obsidian
#

no it's just from the page.tsx then i give everything to a redux store

#
import { setGalaxies, setPlanets, setSolars } from '@/store/productsSlice';
import { store } from '@/store/store';

import Preloader from '@/components/preloader';
import Products from '@/components/products';
import Providers from '@/components/providers';

const processDataAndDispatch = (
  data: any,
  category: any,
  dispatchAction: any
) => {
  const processedData = data.products[category].map((item: any) => {
    return {
      id: item.id,
      title: item.title,
      description: item.description,
      price: item.variants.edges[0].node.price.amount,
      image: item.images.edges[0].node.url,
    };
  });

  store.dispatch(dispatchAction(processedData));
};

export default async function Page() {
  const response = await fetch('/api/items', { next: { revalidate: 20 } });

  const data = await response.json();

  processDataAndDispatch(data, 'planets', setPlanets);
  processDataAndDispatch(data, 'solars', setSolars);
  processDataAndDispatch(data, 'galaxies', setGalaxies);

  const products: any = store.getState().products;
  const planets: any = store.getState().products.planets;
  const solars: any = store.getState().products.solars;
  const galaxies: any = store.getState().products.galaxies;

  const allProducts: any = Object.values(products).flatMap(
    (category: any) => category
  );

  return (
    <Providers>
      <Preloader
        products={allProducts}
        planets={planets}
        solars={solars}
        galaxies={galaxies}
      />
      <Products products={allProducts} />
    </Providers>
  );
}
#

the preloader stores the data for the client side

the products component basically takes the products and displays them and then if i decide to filter it displays from redux store

twin meteor
#

my suggestion is to change the way you are doing your logic

#

remove the api route completely

#

convert it to a regular function

#

dont use redux for storing the data… its not needed

#

filter the result and display it based on the filters

full obsidian
twin meteor
full obsidian
# twin meteor Yeah. You may need redux for that, but not for ALL the items. Thats just bloaty ...

ikr zustand does the job too but i am trying to learn with redux i guess and i switched to redux tbh becuase i saw this video
https://www.youtube.com/watch?v=dRLjoT4r-jc&t=1291s

i had to watch it 5 times just to figure out how to server side render the products and also have them in redux and be interactive 😂

State management can be difficult. Redux in combination with NextJS 13's app directory with React Server Components is like playing the game of state management on maximum difficulty. Let's simplify it! I'll show you how to do Redux with SSR as well as Redux shared with client and the server.

Scribe: https://scribe.how/jackherrington-march
Code...

▶ Play video
twin meteor
full obsidian
#

anyway I appreciate your help so much I will extract the api route logic to the page component then hopefully it's solved

full obsidian
twin meteor
full obsidian
#

just less boilerplate?

twin meteor
#

exactly

#

but use what you like. its not like one is “wrong”

#

just preference 🙂

full obsidian
twin meteor
# full obsidian Yup

make sure to mark answered if you are good to go so people dont need to re-check the question

full obsidian
iron walrusBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1120741735065206794 message)

iron walrusBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1120741735065206794 message)

inland forge
#

wait the bot is malfunctioning