How to access Azure SQL Database which is connected with Azure Static Web apps from Next.js?

Jihoo Byeon 0 Reputation points
2024-05-29T13:29:47.4733333+00:00

Hello, I deployed a Next.js app to Azure Static Web apps, and connected to Azure SQL Server via Azure Portal.

and I tried to use it as explained at https://learn.microsoft.com/ko-kr/azure/static-web-apps/database-azure-sql?tabs=bash&pivots=static-web-apps-rest, but the app fails to fetch from /data-api/ path, both on client and server side.

It seems to collide with Next.js routing… pages’ seems to searching for /pages/data-api/, not /data-api/.

Azure Static Web Apps
Azure Static Web Apps
An Azure service that provides streamlined full-stack web app development.
851 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Pinaki Ghatak 3,265 Reputation points Microsoft Employee
    2024-07-08T10:51:23.3+00:00

    Hello @Jihoo Byeon

    To access Azure SQL Database connected with Azure Static Web Apps from Next.js, you can create an API route in Next.js that fetches data from the database and returns it to the client.

    Based on the error you mentioned, it seems like there might be a routing issue with your Next.js app. By default, Next.js treats any file in the pages directory as a page.

    To avoid this, you can create a pages/api directory and put your API routes there. This will ensure that Next.js treats them as API routes and not pages. Here's an example of how you can create an API route in Next.js to fetch data from Azure SQL Database:

    1. Create a new file in the pages/api directory called data-api.js.
    2. In data-api.js, import the mssql package and create a connection to your Azure SQL Database. Here's an example:
    import sql from 'mssql'; 
    const config = { 
    	server: '.database.windows.net', 
    	database: '', 
    	user: '', 
    	password: '', 
    	options: 
    	{ 
    		encrypt: true, 
    		enableArithAbort: true 
    	} 
    }; 
    export default async function handler(req, res) 
    	{ 
    	try 
    	{ 
    		// Create a new connection pool 
    		const pool = await sql.connect(config); 
    		// Query the database 
    		const result = await pool.request().query('SELECT * FROM '); 
    		// Return the result as JSON 
    		res.json(result.recordset); 
    	} catch (err) 
    	{ 
    		console.error(err); res.status(500).send('Error connecting to database'); 
    	} }
    
    1. In your Next.js app, you can fetch data from this API route using the fetch API.
    0 comments No comments