Enable same site, cookies issue

congar
New Member
3 0 0

I made an app I'm using a custom session but I am still getting an error message you must enable cookies in the browser. any help?
my server.js code:
Screen Shot.png

 

 

 

 

 

 

import '@babel/polyfill';
import dotenv from 'dotenv';
import 'isomorphic-fetch';
import createShopifyAuth, { verifyRequest } from '@shopify/koa-shopify-auth';
import Shopify, { ApiVersion } from '@shopify/shopify-api';
import Koa from 'koa';
import next from 'next';
import Router from 'koa-router';
import koaLogger from 'koa-logger';
import logger from '../logger';
import RedisStore from './redis-store';

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({
    dev
});
const handle = app.getRequestHandler();
// Create a new instance of the custom storage class
const sessionStorage = new RedisStore();

Shopify.Context.initialize({
    API_KEY: process.env.SHOPIFY_API_KEY,
    API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
    SCOPES: process.env.SCOPES.split(','),
    HOST_NAME: process.env.HOST.replace(/https:\/\//, ''),
    API_VERSION: ApiVersion.April21,
    IS_EMBEDDED_APP: true,
    // Pass the sessionStorage methods to pass into a new instance of `CustomSessionStorage`
    SESSION_STORAGE: new Shopify.Session.CustomSessionStorage(
        sessionStorage.storeCallback,
        sessionStorage.loadCallback,
        sessionStorage.deleteCallback
    )
});

// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(async () => {
    const server = new Koa();
    const router = new Router();
    server.keys = [Shopify.Context.API_SECRET_KEY];

    server.use(
        koaLogger((str, args) => {
            logger.info(args);
        })
    );
    server.use(
        createShopifyAuth({
            async afterAuth(ctx) {
                // Access token and shop available in ctx.state.shopify
                const { shop, accessToken, scope } = ctx.state.shopify;
                ACTIVE_SHOPIFY_SHOPS[shop] = scope;

                const response = await Shopify.Webhooks.Registry.register({
                    shop,
                    accessToken,
                    path: '/webhooks',
                    topic: 'APP_UNINSTALLED',
                    webhookHandler: async (topic, shop, body) => delete ACTIVE_SHOPIFY_SHOPS[shop]
                });

                if (!response.success) {
                    console.log(`Failed to register APP_UNINSTALLED webhook: ${response.result}`);
                }

                // Redirect to app with shop parameter upon auth
                ctx.redirect(`/?shop=${shop}`);
            }
        })
    );

    const handleRequest = async (ctx) => {
        await handle(ctx.req, ctx.res);
        ctx.respond = false;
        ctx.res.statusCode = 200;
    };

    router.get('/health', async (ctx) => {
        ctx.res.statusCode = 200;
    });

    router.get('/', async (ctx) => {
        const shop = ctx.query.shop;

        // This shop hasn't been seen yet, go through OAuth to create a session
        if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
            ctx.redirect(`/auth?shop=${shop}`);
        } else {
            await handleRequest(ctx);
        }
    });

    router.post('/webhooks', async (ctx) => {
        try {
            await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
            console.log(`Webhook processed, returned status code 200`);
        } catch (error) {
            console.log(`Failed to process webhook: ${error}`);
        }
    });

    router.post('/graphql', verifyRequest({ returnHeader: true }), async (ctx, next) => {
        await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    });

    router.get('(/_next/static/.*)', handleRequest); // Static content is clear
    router.get('/_next/webpack-hmr', handleRequest); // Webpack content is clear
    router.get('(.*)', verifyRequest(), handleRequest); // Everything else must have sessions

    server.use(router.allowedMethods());
    server.use(router.routes());
    server.listen(port, () => {
        console.log(`> Ready on http://localhost:${port}`);
    });
});

 

 

 

 

 

 

0 Likes
Avi_Ben_Zaken
Tourist
6 0 2

Hey,

how does your app.js look like? maybe you are using Cookies there like in the old way?

 

0 Likes
congar
New Member
3 0 0
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import App from 'next/app';
import { AppProvider } from '@shopify/polaris';
import { Provider, useAppBridge } from '@shopify/app-bridge-react';
import { authenticatedFetch } from '@shopify/app-bridge-utils';
import { Redirect } from '@shopify/app-bridge/actions';
import translations from '@shopify/polaris/locales/en.json';
import { ToastContainer } from 'react-toastify';
import axios from 'axios';
import { store } from '../store/index';
import { getSingleRequest } from '../store/actions/setting';
import { Provider as ReduxProvider } from 'react-redux';
import '@shopify/polaris/dist/styles.css';
import '../assets/css/index.css';
import 'react-toastify/dist/ReactToastify.css';
import ShopWrapper from '../components/wrappers/ShopWrapper';

function userLoggedInFetch(app) {
    const fetchFunction = authenticatedFetch(app);

    return async (uri, options) => {
        const response = await fetchFunction(uri, options);

        if (response.headers.get('X-Shopify-API-Request-Failure-Reauthorize') === '1') {
            const authUrlHeader = response.headers.get(
                'X-Shopify-API-Request-Failure-Reauthorize-Url'
            );

            const redirect = Redirect.create(app);
            redirect.dispatch(Redirect.Action.APP, authUrlHeader || `/auth`);
            return null;
        }

        return response;
    };
}

function MyProvider(props) {
    const app = useAppBridge();

    const client = new ApolloClient({
        fetch: userLoggedInFetch(app),
        fetchOptions: {
            credentials: 'include'
        }
    });

    const Component = props.Component;

    return (
        <ApolloProvider client={client}>
            <ShopWrapper>
                <Component {...props} />
            </ShopWrapper>
        </ApolloProvider>
    );
}

const apiKey = process.env.APIKEY;
const baseUrl = process.env.URL;

axios.defaults.baseURL = baseUrl;
axios.defaults.headers.common['api_key'] = apiKey;

class MyApp extends App {
    render() {
        const { Component, pageProps, shopOrigin } = this.props;

        return (
            <ReduxProvider store={store}>
                <AppProvider i18n={translations}>
                    <Provider
                        config={{
                            apiKey: API_KEY,
                            shopOrigin: shopOrigin,
                            forceRedirect: true
                        }}>
                        <MyProvider Component={Component} {...pageProps} />
                        <ToastContainer />
                    </Provider>
                </AppProvider>
            </ReduxProvider>
        );
    }
}

MyApp.getInitialProps = async ({ ctx }) => {
    return {
        shopOrigin: ctx.query.shop
    };
};

export default MyApp;
0 Likes
Avi_Ben_Zaken
Tourist
6 0 2

thats wierd, i'm trying now the new guide so i'll let you know if i'm having the same issue.

Avi_Ben_Zaken
Tourist
6 0 2

Hey all,

I'm using all new shopify api's, working with session tokens and still have the 'Enable Cookies' banner.

I noticed it's happening after restarting the server and I can see on my ngrok a GET call to /auth/enable_cookies, with no reason, of course.

Since I'm 100% not using cookies, I started to search under that "koa-shopify-auth" pack.

Found that code:

                    "case 14:
                        if (!(ctx.path === enableCookiesPath)) return [3 /*break*/16];
                        return [4 /*yield*/enableCookies(ctx)];"
 
at node_modules\@shopify\koa-shopify-auth\dist\src\auth\index.js
 
Change "enableCookies(ctx)" to "next()" and problem fixed.
I'm on the latest "@shopify/koa-shopify-auth""^4.1.3" so I don't see any other solution.
Be aware - It's not recommended to change node_modules so if you use this solution don't forget to reEdit it whenever you reInstall it.
0 Likes