fetch pdf from strapi using nextjs
To fetch a PDF from Strapi using Next.js, you'll need to perform the following steps:
Set up your Next.js project:
If you haven't already, create a new Next.js project using the command line:
npx create-next-app my-pdf-app cd my-pdf-app
Install required packages:
Next.js uses Axios to make HTTP requests, so you'll need to install it:
npm install axios
Set up API routes in Next.js:
Create a new folder called "pages/api" in your project root.
Inside the "pages/api" folder, create a new file named "pdf.js" (or any other appropriate name).
This file will handle the API route to fetch the PDF from Strapi.
Implement the API route: In the "pdf.js" file, you can use Axios to fetch the PDF data from your Strapi server:
import axios from 'axios'; export default async function handler(req, res) { if (req.method !== 'GET') { return res.status(405).json({ message: 'Method Not Allowed' }); } try { // Replace 'YOUR_STRAPI_ENDPOINT' with your actual Strapi API endpoint const response = await axios.get('YOUR_STRAPI_ENDPOINT/your-pdf-endpoint'); // Assuming Strapi is sending the PDF data in the response's data field const pdfData = response.data; // Set the response headers to specify that the content is a PDF res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment; filename="your-pdf-filename.pdf"'); // Return the PDF data as the response body res.send(pdfData); } catch (error) { console.error(error); res.status(error.response?.status || 500).json({ message: 'Error fetching PDF' }); } }
Note: Make sure to replace 'YOUR_STRAPI_ENDPOINT' with the actual URL of your Strapi server and 'your-pdf-endpoint' with the appropriate endpoint for fetching the PDF from Strapi.
Create a link to download the PDF: In your Next.js component, you can create a link that points to the API route you just created:
import React from 'react'; const MyPDFComponent = () => { return ( <div> <h1>My PDF Page</h1> <a href="/api/pdf" target="_blank" rel="noopener noreferrer">Download PDF</a> </div> ); }; export default MyPDFComponent;
When a user clicks on the "Download PDF" link, it will trigger the API route, which fetches the PDF from Strapi and initiates the download.
Remember to adjust the code according to your specific Strapi API setup and requirements. Ensure that your Strapi server allows public access to the endpoint you are using to fetch the PDF. Additionally, consider adding authentication and authorization if needed, especially if the PDF contains sensitive information.