Hi,
I am trying to create a shopify app that can post a blog, I have started with the default template using Shopify CLI and modified the app._index.jsx file to the following:
import { useEffect } from "react";
import { json } from "@remix-run/node";
import { shopify } from '@shopify/shopify-app-remix';
import { getSession } from '@shopify/shopify-app-remix/server';
import fetch from "node-fetch"; // Ensure you have 'node-fetch' installed for making fetch requests in Node.js
import { useActionData, useNavigation, useSubmit } from "@remix-run/react";
import {
Page,
Layout,
Text,
Card,
Button,
BlockStack,
Box,
Link,
InlineStack,
} from "@shopify/polaris";
import { authenticate } from "../shopify.server";
export const loader = async ({ request }) => {
await authenticate.admin(request);
return null;
};
export const action = async ({ request }) => {
const session = await getSession(request.headers.get('Cookie'));
const accessToken = session.accessToken;
const shop = session.shop;
// Now use the accessToken to make a Shopify API call
const url = `https://${shop}/admin/api/2022-01/blogs/${BLOG_ID}/articles.json`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken,
},
body: JSON.stringify({
article: {
title: "Your Blog Title",
body_html: "<p>Your blog content here</p>",
},
}),
});
if (!response.ok) {
throw new Error(`Failed to publish blog post: ${response.statusText}`);
}
const data = await response.json();
return data;
};
export default function Index() {
const nav = useNavigation();
const actionData = useActionData();
const submit = useSubmit();
const isLoading =
["loading", "submitting"].includes(nav.state) && nav.formMethod === "POST";
const blogPostId = actionData?.blogPost?.id;
useEffect(() => {
if (blogPostId) {
}
}, [blogPostId]);
const createBlogPost = () => submit({}, { replace: true, method: "POST" });
return (
<Page>
<ui-title-bar title="Blog Post AI">
</ui-title-bar>
<BlockStack gap="500">
<Layout>
<Layout.Section>
<Card>
<BlockStack gap="500">
<Text as="h2" variant="headingMd">
Publish a New Blog Post
</Text>
<Button loading={isLoading} onClick={createBlogPost}>
Publish Post
</Button>
{actionData?.blogPost && (
<Box padding="400" background="bg-surface-active">
<pre>
<code>{JSON.stringify(actionData.blogPost, null, 2)}</code>
</pre>
</Box>
)}
</BlockStack>
</Card>
</Layout.Section>
</Layout>
</BlockStack>
</Page>
);
}
Currently this code doesn’t work as I am struggling to get the access token which I have tried tro get it from the session using:
const session = await getSession(request.headers.get('Cookie'));
But I get the following error message:
TypeError: (0 , import_server3.getSession) is not a function
I am not sure if this is the correct way to get the access token or should I be using another way to obtain the token to then post a blog.
Thanks