Giter Site home page Giter Site logo

sample-app-nodejs's Introduction

NextJS Sample App

This starter app includes all the files necessary to get started with a basic, hello world app. This app uses NextJS, BigDesign, Typescript, and React.

Running the app in development

To get the app running locally, follow these instructions:

  1. Use Node 18+ and NPM 8+. To check the running versions, use the following commands:
node -v
npm -v
  1. Clone and/or fork the repo and install npm packages:
git clone [email protected]:bigcommerce/sample-app-nodejs.git my-bigcommerce-app
cd my-bigcommerce-app
npm install
  1. To expose your app server using an HTTP tunnel, install ngrok globally, then start the ngrok service.

You can use npm to install ngrok:

npm install -g ngrok

Alternatively, MacOS users can use the homebrew package manager:

brew install ngrok

Start ngrok on port 3000 to expose the default Next.js server:

ngrok http 3000
  1. Use the BigCommerce Developer Portal to register a draft app. For steps 5-7, enter callbacks as 'https://{ngrok_url}/api/{auth || load || uninstall}'. Get the ngrok_url from the ngrok terminal session.
https://12345.ngrok-free.app/api/auth # auth callback
https://12345.ngrok-free.app/api/load # load callback
https://12345.ngrok-free.app/api/uninstall # uninstall callback
  1. Copy .env-sample to .env.
cp .env-sample .env
  1. In the .env file, replace the CLIENT_ID and CLIENT_SECRET variables with the API account credentials in the app profile. To locate the credentials, find the app's profile in the Developer Portal, then click View Client ID.

  2. In the .env file, update the AUTH_CALLBACK variable with the ngrok_url from step 4.

  3. In the .env file, enter a secret JWT_KEY. To support HS256 encryption, the JWT key must be at least 32 random characters (256 bits).

  4. Configure the data store. In the .env file, specify the DB_TYPE.

    The DB type must be either firebase or mysql.

    If using Firebase, supply the FIRE_ config keys listed in the .env file. See the Firebase quickstart (Google).

    If using MySQL, supply the MYSQL_ config keys listed in the .env file, then do the initial database migration by running the following npm script:

npm run db:setup
  1. Start your dev environment in a dedicated terminal session, separate from ngrok.
npm run dev

If ngrok expires, update the callbacks in steps 4 and 7 with the new ngrok_url. You can learn more about persisting ngrok tunnels longer (ngrok).

  1. Consult our developer documentation to install and launch the app.

Production builds

In production, you must build and run optimized version of the code. Use the following commands to get started:

When you run the start script, specify a port number using the -p flag. Otherwise, the process will fail.

npm run build
npm run start -p 3000

sample-app-nodejs's People

Contributors

bc-chaz avatar bc-nekisham avatar bc-zachary avatar bookernath avatar cale-sweeney avatar chanceaclark avatar christensenep avatar dependabot[bot] avatar hatertron3000 avatar mariajose avatar rtalvarez avatar slsriehl avatar snyk-bot avatar tylerbroadway avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

sample-app-nodejs's Issues

Getting JWT error while making API request

Can somebody help me what i missed? I'm trying to make an API call. I'm getting error saying "JWT must be provided"

500 error

I have given H-256 JWT key on my .env file. and installed required package.
sample JWT key

eyJhbGciOiJIUzI1NiJ9.eyJSb2xlIjoiQWRtaW4iLCJJc3N1ZXIiOiJQcmF2YWFoIGNvbnN1bHRpbmciLCJVc2VybmFtZSI6IlF1YW50dW0gd2lkZ2V0cyIsImV4cCI6MTcxMDIyMDU4NSwiaWF0IjoxNzEwMjIwNTg1fQ.2oL5nvFGLbYEVNN_zvuUTcW-jBQzLeTvCjU5COxFRR0

Can anyone tell me where i am missing out?

Tutorial Error - Unexpected token '.' in ButtonGroup.js

Following the first step of the tutorial (Step 1: Set up Your Local Environment) returns an error when running the local dev server.

M1 macOS 12.3

Server Error
SyntaxError: Unexpected token '.'

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
<unknown>
/Path/to/App/node_modules/ (bigcommerce/big-design/dist/cjs/components/ButtonGroup/ButtonGroup.js (55)
wrapSafe
internal/modules/cjs/loader.js (915:16)
Module._compile
internal/modules/cjs/loader.js (963:27)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1027:10)
Module.load
internal/modules/cjs/loader.js (863:32)
Function.Module._load
internal/modules/cjs/loader.js (708:14)
Module.require
internal/modules/cjs/loader.js (887:19)
require
internal/modules/cjs/helpers.js (74:18)
Object.<anonymous>
file:////Path/to/App/node_modules/@bigcommerce/big-design/dist/cjs/components/ButtonGroup/index.js (7:20)
Module._compile
internal/modules/cjs/loader.js (999:30)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1027:10)

Getting errors whit template app

Im getting error on this app on the load of the products, on my Ngrok i'm getting error GET 500 on the end point

GET /API/products/list 500 interntal Server Error

otherwise, I didn't have a DB integrated whit my sample-app-nodejs/next

Unexpected end of JSON input get data from base customer side.

I have a problem when I request the database. I have written an API request and a hook. On the server side, everything is fine; I receive all the data in the database. However, when I use the hook for the user part, I receive an empty response. The request status is 200, but there is no data.

Get All Scripts GET https://api.bigcommerce.com /stores/{store_hash}/v3/content/scripts response undefined.

I am using this repo I am trying to get the list of scripts before reading the script I have created the script successfully using this ref. https://developer.bigcommerce.com/api-reference/99ba5fd00ad56-create-a-script

I can see the js loaded on storefronts but when I query big commerce it gave me a response undefined.

 // get list of scripts 
      const { data_read_sc } = await bigcommerce.get('/content/scripts');
      console.log(" reading the script  ",data_read_sc)

Output

reading the script   undefined

Issues deploying to Heroku

When deploying to Heroku, getting this error (below). Any thoughts on how to fix it?

-----> Installing dependencies
Installing node modules
npm ERR! code EINTEGRITY
npm ERR! sha512-oU39CH8fMpZw/QHAlfYgaceTM7kPHBbVPiJvKzSKtlkzYixAaB97UwReN1IKF+kdLL/tIOZDGKRZoJS5ZyAkNA== integrity checksum failed when using sha512: wanted sha512-oU39CH8fMpZw/QHAlfYgaceTM7kPHBbVPiJvKzSKtlkzYixAaB97UwReN1IKF+kdLL/tIOZDGKRZoJS5ZyAkNA== but got sha512-BtCkKT5/o5gGLHE78+zP84J0XhTYLNdhXEdFwwsDPKLeQ0P9dyjk3lc801oY3lj32see/nZdpfTkI8u4WyGPBw==. (11161 bytes)

   npm ERR! A complete log of this run can be found in:
   npm ERR!     /tmp/npmcache.BpYmC/_logs/2022-01-09T08_29_06_464Z-debug.log

-----> Build failed

   We're sorry this build is failing! You can troubleshoot common issues here:
   https://devcenter.heroku.com/articles/troubleshooting-node-deploys
   
   If you're stuck, please submit a ticket so we can help:
   https://help.heroku.com/
   
   Love,
   Heroku

! Push rejected, failed to compile Node.js app.
! Push failed

`mysql` package auth protocol not supported by MySQL 8

Description

Running npm run db:setup when attempting to connect to a MySQL 8 database throws the following error:

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

The error above is best explained by: mysqljs/mysql#2233

TL;DR: The mysqljs/mysql npm package does not support new authentication protocols introduced in MySQL 8. Until the PR above is merged, users will continue to receive the error above. The sample-app-nodejs documentation does not call out that MySQL 8 is not supported, which results in confusion from consumers of this app.

Workarounds (Do Not Use in Production)

NOT RECOMMENDED FOR PRODUCTION, POTENTIAL SECURITY RISKS: https://stackoverflow.com/a/50131831/8211101

As explained by https://stackoverflow.com/a/56509065/8211101, running the command in the SO answer above negates the benefits of using MySQL 8's more secure authentication methods.

Potential Solution (Needs Investigation)

Until the mysqljs/mysql PR is merged to support MySQL 8's new pluggable authentication methods, the mysql package will continue to throw this error when trying to connect to a MySQL 8 database.

The mysql2 npm package (https://www.npmjs.com/package/mysql2) shares the same API as the mysql npm package, and does support the new authentication methods. This could be researched as a potential option to replace mysql. If mysql2 is backwards compatible with older MySQL versions, that would be ideal. Otherwise, we might need to call out that mysql should be used for MySQL < 8 (need to verify which version mysql breaks on), and that mysql2 should be used for MySQL 8+.

Best practice for authentication

Hey team,

I'm posting this discussion here in lieu of having anywhere better. I hope that's ok!

We have Laravel + React apps that make use of cookies for authentication. As per your recent article, this suffers from being blocked in some browsers. We do our best to detect cookies being blocked and request that people open in a new tab to force a first-party context.

We have an unreleased improvement which adds partitioned cookie support so that we remain compatible in Chrome. It already works fine in Firefox as third-party cookies are automatically partitioned per requesting domain. Unfortunately, providing compatibility with Safari is still very difficult as it requires a separate method requestStorageAccess which requires the user to have visited the domain in a first-party context and interacted with the page within the last 30 days. I'm loathed to invest the resources to create this sub-par experience.

This has led me to reconsider the cookieless approach, but I cannot currently see a way forward that isn't susceptible to a security flaw and so I wanted to look to you for guidance.

My understanding is that when using the JWT approach, whether it's stored on a URL as per this repo, or stored in local storage/session storage, the credentials are visible to any JS and so I believe it's susceptible to being stolen through XSS.

(Again, from my research, JWT best practice is to deliver as an HTTP only, secure cookie (preferably also with SameSite strict to mitigate CSRf) but this route is not available to us for obvious reasons).

From my research outside of BigCommerce, some people suggest issuing JWTs with a short life and then providing a long-life refresh token but we have no way to deliver a refresh token in a manner that doesn't have the same security weakness.

Are you aware of another option to protect against XSS when using the JWT approach recommended in this app?

Many thanks.

JWT Not active

Captura de pantalla (103)

Hi! I'm following all the steps of the process to run this project for creating a shipping application, and I always receive this error after installing the application on my store

All the URLs for Authentication, load and uninstall are correct, using the ngrok ID after run ngrok http 3000

What could be the problem?

Cheers

cart data

I want to kno if it is possible to access the cart data through the App?
I'm asking because i'm developing an app to read cart data. But whenever a press the button i get 401 error:

const fetchBigCommerceData = async () => {
try {
const response = await fetch(
"https://api.bigcommerce.com/stores/aherf0o3nw/v3/carts/{CartId}",
{
headers: {
"Accept" : "application/json",
"Content-Type" : "application/json",
"X-Auth-Token" : "4*****************************,
"X-Auth-Client" : "a*****************************",
},
mode: "no-cors",
}
);

how to intract with store front cart data using the theme app extension or script tag api.

Hi, community,

I am using this repo it was working fine.

I can't find any office doc reference for the interact with a storefront.
how to do?

thanks for the help.

here is code example

I create the new page

import { useState } from 'react';
import { NextApiRequest, NextApiResponse } from 'next';
import { bigcommerceClient, getSession } from '../lib/auth';
import * as BigCommerce from 'node-bigcommerce';
import { Box, Flex, H1, H4, Panel } from '@bigcommerce/big-design';
import styled from 'styled-components';
import ErrorMessage from '../components/error';
import Loading from '../components/loading';
import { useScripttag } from '../lib/hooks';

const cartbtnPage = (req: NextApiRequest, res: NextApiResponse) => {
    const [response, setResponse] = useState(null);
    const { error, isLoading, summary } = useScripttag();
    

    if (isLoading) return <Loading />;
    if (error) return <ErrorMessage error={error} />;

  
    const handleClick = async () => {
    //   const client = new BigCommerce({
    //     secret: process.env.,
    //     accessToken: ,
    //     storeHash: ,
    //   });
  
      try {

           const { accessToken, storeHash } = await getSession(req);
        const bigcommerce = bigcommerceClient(accessToken, storeHash, 'v3');

        const { data } = await bigcommerce.post('/script_tags', {
            script: `
              var button = document.createElement("button");
              button.innerHTML = "Store Front Button";
              button.onclick = function () {
                alert("Button clicked!");
              };
              document.body.appendChild(button);
            `,
            event: 'onload',
            scope: 'storefront'
          })
            .then(response => console.log(response.data))
            .catch(error => console.error(error));


        // // res.status(200).json(data);
        // console.log(data)
        // const result = await bigcommerce.post('/script_tags', {
        //   script_tag: {
        //     src: 'https://example.com/script.js',
        //     event: 'onload',
        //     display_scope: 'storefront',
        //   },
        // });
        console.log(" this is run ");
        //  setResponse(result);
        setResponse("result");
      } catch (error) {
        console.error(error);
      }
    };
  
    return (
      <div>
        <button onClick={handleClick}>Create Script Tag</button>
        {response && (
          <p>
            Script tag created! ID: {response}
          </p>
        )}
       
      </div>
      
    );
  };
 

  export default cartbtnPage;

Error I am getting
image

here is terminal Error log

wait  - compiling /cartbtnPage (client and server)...
warn  - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works
error - ./node_modules/mysql/lib/Connection.js:3:0
Module not found: Can't resolve 'net'

Import trace for requested module:
./node_modules/mysql/index.js
./lib/dbs/mysql.ts
./lib/db.ts
./lib/auth.ts
./pages/cartbtnPage.tsx

https://nextjs.org/docs/messages/module-not-found
Could not find files for /cartbtnPage in .next/build-manifest.json

[Solved] Heroku build fails

When I try to deploy the app I get the following error:

-----> Installing dependencies
       Installing node modules
       npm ERR! code EINTEGRITY
       npm ERR! sha512-oU39CH8fMpZw/QHAlfYgaceTM7kPHBbVPiJvKzSKtlkzYixAaB97UwReN1IKF+kdLL/tIOZDGKRZoJS5ZyAkNA== integrity checksum failed when using sha512: wanted sha512-oU39CH8fMpZw/QHAlfYgaceTM7kPHBbVPiJvKzSKtlkzYixAaB97UwReN1IKF+kdLL/tIOZDGKRZoJS5ZyAkNA== but got sha512-BtCkKT5/o5gGLHE78+zP84J0XhTYLNdhXEdFwwsDPKLeQ0P9dyjk3lc801oY3lj32see/nZdpfTkI8u4WyGPBw==. (11161 bytes)
       
       npm ERR! A complete log of this run can be found in:
       npm ERR!     /tmp/npmcache.5Jgej/_logs/2022-02-22T15_11_43_601Z-debug.log
-----> Build failed
       
       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys
       
       Some possible problems:
       
       - Dangerous semver range (>) in engines.node
         https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
       
       Love,
       Heroku
       
 !     Push rejected, failed to compile Node.js app.
 !     Push failed

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.