'Session was not valid' after restarting app server

Hello Shopify Community! :grin:

Since I deployed my Shopify App I encounter following error in the Backend after restarting the server:

Session was not valid. Redirecting to /api/auth?shop=myshop-dev.myshopify.com | {shop: myshop-dev.myshopify.com}

It seems like all sessions get deleted when restarting the server and strangely, in my App I don’t get redirected to authenticate again but I just see a white screen.

Some extra information:

  1. Reinstalling the app solves the problem short-term (until restarting the server again)
  2. I created the App based on the boilerplate code of the Shopify CLI
    1. I set up sessionStorage as a SQLiteSessionStorage when creating the Shopify app object
  3. In the local environment I didn’t encounter this problem
  4. The App Frontend is made in VueJS and I stripped any React components
    1. Although authentication seems to fail the code of the frontend still gets executed (I see my console.log statements of the frontend)

The questions I have:

  • Which session is not valid? The one used to make authenticated requests or the one connected to the OAuth token that gets generated when installing the App?
  • Am I supposed to save the session persistently instead of using the SQLiteSessionStorage?
  • Is it possible that I don’t get redirected to reauthenticate properly because I use VueJS with its router in the Frontend or is this redirection happening in the Backend?

This is how the authentication is setup right now:

/web/index.js

// -check
import { join } from "path";
import { readFileSync } from "fs";
import express from "express";
import serveStatic from "serve-static";

import useProductRoutes from "./routes/product.js";
import useFilesRoutes from "./routes/files.js";

import shopify from "./shopify.js";
import webhookHandlers from "./webhook-handlers.js";

// -ignore
const PORT = parseInt(process.env.BACKEND_PORT || process.env.PORT, 10);

const STATIC_PATH =
  process.env.NODE_ENV === "production"
    ? `${process.cwd()}/frontend/dist`
    : `${process.cwd()}/frontend/`;

const app = express();

// Set up Shopify authentication and webhook handling
app.get(shopify.config.auth.path, shopify.auth.begin());
app.get(
  shopify.config.auth.callbackPath,
  shopify.auth.callback(),
  shopify.redirectToShopifyOrAppRoot()
);
app.post(
  shopify.config.webhooks.path,
  // -ignore
  shopify.processWebhooks({ webhookHandlers })
);

// All endpoints after this point will require an active session
app.use("/api/*", shopify.validateAuthenticatedSession());

app.use(express.json());

useFilesRoutes(app);
useProductRoutes(app);

app.use(serveStatic(STATIC_PATH, { index: false }));

app.use("/*", shopify.ensureInstalledOnShop(), async (_req, res, _next) => {
  return res
    .status(200)
    .set("Content-Type", "text/html")
    .send(readFileSync(join(STATIC_PATH, "index.html")));
});

app.listen(PORT);

/web/shopify.js

import { BillingInterval, LATEST_API_VERSION } from "@shopify/shopify-api";
import { shopifyApp } from "@shopify/shopify-app-express";
import { SQLiteSessionStorage } from "@shopify/shopify-app-session-storage-sqlite";
import { restResources } from "@shopify/shopify-api/rest/admin/2023-01";

const DB_PATH = `${process.cwd()}/database.sqlite`;

const shopify = shopifyApp({
  api: {
    apiVersion: LATEST_API_VERSION,
    restResources,
    billing: undefined, // or replace with billingConfig above to enable example billing
  },
  auth: {
    path: "/api/auth",
    callbackPath: "/api/auth/callback",
  },
  webhooks: {
    path: "/api/webhooks",
  },
  // This should be replaced with your preferred storage strategy
  sessionStorage: new SQLiteSessionStorage(DB_PATH),
});

export default shopify;

Hi Benjaminka,

This is strange behaviour but there’s a few things we can look at for troubleshooting. I’ll answer your questions below:

  1. Which session is not valid? The session that is not valid would be the user’s session, which includes the OAuth token. When you authenticate with Shopify, a user session is created, and this session needs to be valid for your app to make authenticated requests to Shopify’s API on behalf of the user.

  2. Am I supposed to save the session persistently instead of using the SQLiteSessionStorage? You’re already using SQLiteSessionStorage which is a persistent storage. However, you need to ensure that the session data is being stored and retrieved correctly, and that your app has the correct permissions to read/write to this location. If the sessions are not being stored correctly in SQLite when your server restarts, it would explain why the sessions are not valid.

  3. Is it possible that I don’t get redirected to reauthenticate properly because I use VueJS with its router in the Frontend or is this redirection happening in the Backend? The redirection to reauthenticate is handled in the backend. Your frontend framework (VueJS in this case) should not affect this.

Some ideas for debugging this:

  • Make sure that your SQLite database is being written to and read from correctly.
  • Check the session data that is being stored in your SQLite database. Does it include the necessary information (like the access token)
  • Log the requests and responses in your shopify.auth.begin() and shopify.auth.callback() middleware. Are you receiving the correct data?
  • Look at the network tab in your browser’s developer tools when you’re being redirected to Shopify for authentication. Are there any errors?

Hope this helps!

Hello Liam! Thanks for your concise answer. Thanks to it I was able to pin the problem which seems to be caused not by any code performing the session validation but rather by the way the App was deployed. I followed the Shopify guide on how to deploy a App and it didn’t mention that when deploying with fly.io every machine restart resets the state so that everything is set back to its initial values, including the database.

What happened is that after installing the App, the record was added to the sqlite database containing the new access token. On restarting the machine that database was reset causing the new access token to be lost and thus the App not to recognize the shop. For now I fixed it by installing the app while in local and then deploying.

@Benjaminka , I am too facing the same problem, Can you please explain me how you have handled this session issue.
FYI , I too created the App based on the boilerplate code of the Shopify CLI.
Have you made any changes to db.server.js file, Please help me in fixing this issue.

Hello @Thesingh_TM , I don’t recall a db.server.js file but I fixed it by setting up a volume in the Fly.io app and putting the .sqlite file inside it to make it persistent because for some reason the guide did not explain that a volume is needed for pesistent information

Thanks @Benjaminka , This worked for me.

Hi ,

I am developing a react node app App working on fine on local but I when I transfer the code to Live server getting session not valid error. My database is PostgreSQL
Any help will be appreciated

Hi @sibTech_synergy
Did you solve the error?